当* ngFor以角度2结束时执行函数 [英] execute a function when *ngFor finished in angular 2
问题描述
我尝试用角度2创建一个应用程序,我想要在* ngFor中渲染最后一个元素时,执行一个函数,如下所示:
I trying to create a application with angular 2,i want when last element rendered in *ngFor,execute a function, somthing like this :
<ul>
<li *ngFor="#i of items">{{i.text}}</li> <==== i want when this completed, execute a functuon in my class
</ul>
谢谢。
推荐答案
更新
您可以为此目的使用 @ViewChildren
有三种情况
1. 初始化 ngFor
元素不是因为 ngIf
而在它上面或者它的父元素
1. on initialization ngFor
element is not rendred due to ngIf
on it or it's parent
- in在哪种情况下,当
ngIf
变得真实时,您将收到ViewChildren
订阅
的通知
- in which case, whenver
ngIf
becomes truthy, you will be notified by theViewChildren
subscription
2。初始化 ngFor
元素是rendred而不管 ngIf
或它的父母
2. on initialization ngFor
element is rendred regardless of ngIf
on it or it's parent
- 在这种情况下
ViewChildren
订阅不会第一次通知您,但您可以确定它是在ngAfterViewInit
hook
- in which case
ViewChildren
subscription will not notify you for the first time, but you can be sure it's rendered in thengAfterViewInit
hook
3. 在 ngFor
数组中添加/删除项目
3. items are added/removed to/from the ngFor
Array
- 在这种情况下,
ViewChildren
订阅会通知你
- in which case also
ViewChildren
subscription will notify you
[Plunker Demo] (请参阅控制台日志)
@Component({
selector: 'my-app',
template: `
<ul *ngIf="!isHidden">
<li #allTheseThings *ngFor="let i of items; let last = last">{{i}}</li>
</ul>
<br>
<button (click)="items.push('another')">Add Another</button>
<button (click)="isHidden = !isHidden">{{isHidden ? 'Show' : 'Hide'}}</button>
`,
})
export class App {
items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
@ViewChildren('allTheseThings') things: QueryList<any>;
ngAfterViewInit() {
this.things.changes.subscribe(t => {
this.ngForRendred();
})
}
ngForRendred() {
console.log('NgFor is Rendered');
}
}
。
.
你可以这样做(但请参阅自己的副作用)
You can do it like this ( but see the side Effects for yourself )
<ul>
<li *ngFor="let i of items; let last = last">{{i}} {{last ? callFunction(i) : ''}}</li>
</ul>
无用,除非与 changeDetectionStrategy一起使用。 OnPush
然后您可以控制更改检测的次数,从而控制您的函数被调用的次数。
Then you can have control over how many times change detection occurs, hence how many times your function is called.
ie: 您可以触发下一个 changeDetection
项目
的数据发生变化,您的函数将正确显示真实更改<
i.e: You can trigger next changeDetection
when the data of items
changes, and your function will give proper indication that ngFor
is rendered for real change.
这篇关于当* ngFor以角度2结束时执行函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!