Home > Software engineering >  Logic to show or hide element using angular
Logic to show or hide element using angular

Time:06-10

so I got some problem in logic to show or hide the element.

I have this function to show or hide the "span" element, by that I can show different color on each text.

startWritting() {
// const spanOne = <HTMLInputElement>document.getElementById('one');
// const spanTwo = <HTMLInputElement>document.getElementById('two');
// const spanThree = <HTMLInputElement>document.getElementById('three');
// const spanFour = <HTMLInputElement>document.getElementById('four');

const durCharFwd = 0.1; // character typed
const durFullGap = 2000; // time between typed/delete
const durCharBwd = 0.8; // character deleted
const durDoneGap = 1000;
let strings = ['Your value', 'Organic', 'Gluteen-free', 'Fair-trade'];
let durTotal;
setInterval(() => {
  strings.forEach((string, i) => {
    durTotal =
      string.length * (durCharFwd   durCharBwd)   durFullGap   durDoneGap;
    setInterval(() => {
      this.elements.forEach((el, index) => {
        if (index === i) {
          el.isSelected = true;
        } else {
          el.isSelected = false;
        }
      });
    }, durTotal);
  });
}, durTotal);

}

and heres my HTML code

<ng-container *ngFor="let el of elements">
        <span
          *ngIf="el.isSelected"
          [id]="el.id"
          
        ></span>
      </ng-container>

Bytheway this is to edit the element on typewritting animation as you can see the full html and css animation code here https://codepen.io/matadantelinga/pen/ExQeqjj I wonder if anyone here can advise me on the logic??

CodePudding user response:

Does something like that helps ?

https://stackblitz.com/edit/angular-ivy-cr9lq4?file=src/app/app.component.html,src/app/app.component.ts,src/app/app.component.css

export class AppComponent {
  name = 'Angular '   VERSION.major;

  text = '';
  color = '';

  texts = ['One', 'Two', 'Three', 'Four'];
  colors = ['cyan', 'lightgreen', 'salmon', 'coral'];

  constructor(private cdRef: ChangeDetectorRef) {}

  ngOnInit() {
    timer(0, 500)
      .pipe(map((i) => i % 4))
      .subscribe((i) => {
        this.text = this.texts[i];
        this.color = this.colors[i];
        this.cdRef.detectChanges();
      });
  }
}

EDIT Added the typer to the stackblitz

https://stackblitz.com/edit/angular-ivy-cr9lq4?file=src/app/app.component.html,src/app/app.component.ts,src/app/app.component.css

CodePudding user response:

just declare an array colors

colors=['red','blue','yellow','green']

Just only add [style.color]="colors[i%colors.length]"

<ng-container *ngFor="let el of elements;let i=index">
        <span *ngIf="el.isSelected"
          [style.color]="colors[i%colors.length]"
          [id]="el.id"
          
        ></span>
</ng-container>
  • Related