Call the function after completion * ngFor

I am trying to create an application with angular 2; I want the last element to appear in * ngFor, execute a function, something like this, <img> :

 <img *ngFor="let image of template.previewImages; let i = index" [src]="image" [class.hs_visible]="i==0" /> 

Function name

 animation(){console.log('enter');} 
+5
source share
3 answers

See this Plunker for the solution I managed to come up with.

It may not be elegant, but it (mostly) works!

Basically, *ngFor provides several values , such as the index, even, odd, and, fortunately, the first and last Boolean that evaluate to true for the corresponding iterations. First, you must set the values ​​as local variables in *ngFor just like the index. Then you should get Angular to call the function from the template, which you can do as if you were binding the value to the template, but with a tertiary conditional value (which returns null for false evaluations).

 <div *ngFor="let i of stuff; let l = last "> {{ i }} {{ l === true ? callOnLastIteration() : null}} </div> 

I say: "(basically) it works," because it seems that if you try to bind a property inside a *ngFor -ed element other than the one you are repeating, and then changing the value of the specified property inside the function called on the last iteration, You will receive unwanted behavior and errors in the Angular change distribution system. See Plunker for more details.

0
source

It would be better if you could create a directive that will do the same. You just need to pass the last flag to the directive, and it will call the desired function when rendering the last element.

View

 <p class="my-element" *ngFor="let i of stuff; let l = last" [lastElement]="l" (lastFunc)="test()"> {{i}} </p> 

Directive

 import { Directive, ElementRef, Input, Output, EventEmitter } from '@angular/core'; @Directive({ selector: '[lastElement]' }) export class LastElementDirective { @Input() lastElement : any; @Output() lastFunc = new EventEmitter(); constructor(private el: ElementRef) { this.setTimer(); //somehow lastElem value is available on next tick } setTimer(){ setTimeout(() => { if(this.lastElem) this.lastFunc.emit(); }, 0); } } 

Plunkr in action

0
source

Pankay Parkar works, but you need to change the lastElement entry in the setTimeout function (now it is lastElem , so the plunker does not work to check if the last element is * ngFor)

0
source

Source: https://habr.com/ru/post/1257560/


All Articles