Tom
Tom

Reputation: 4033

Property disappear after reached condition in setInterval()

I have multiple span that are supposed to fade in consecutively. To do so I stated the following in HTML:

<span class="word d-inline-flex" *ngFor="let word of words; let i = index">
      <span class="start-animation" [class.enter-animation]="i <= word$">{{word}}&nbsp;</span>
</span>

The span shall stay after the animation.

To display the consecutively:

word$ = 0;

ngAfterViewInit() {
    this.interval = setInterval( () => {
      this.word$ = this.word$ < this.words.length ? this.word$ + 1 : clearInterval(this.interval);
    }, 100);
}

The animation works, but the spans disappear again. Inspecting the code with Augury I found that after reaching the word length, the property word$ disappears - hence the issue?

Additionally the console returns:

ERROR in src/app/front/text-top/text-top.component.ts(27,7): error TS2322: Type 'number | void' is not assignable to type 'number'. Type 'void' is not assignable to type 'number'.

Upvotes: 1

Views: 80

Answers (1)

korteee
korteee

Reputation: 2682

This happens because you initally set the word$ = 0 to be of type number and then at the ternary statement you set it to be the output of the clearInterval which is a void.

I don't know how exactly your animation works but changing the code to the following might fix the problem.

From this:

this.word$ = this.word$ < this.words.length ? this.word$ + 1 : clearInterval(this.interval);

To this:

if(this.word$ < this.words.length) {
   this.word$++;
} else {
   clearInterval(this.interval)
}

Upvotes: 2

Related Questions