当*ngFor以角度2结束时执行函数

Ali*_*ade 30 javascript angular

我试图用角度2创建一个应用程序,我想在*ngFor中呈现最后一个元素时,执行一个函数,像这样:

<ul>
  <li *ngFor="#i of items">{{i.text}}</li> <==== i want when this completed, execute a functuon in my class
</ul>
Run Code Online (Sandbox Code Playgroud)

谢谢.

Ank*_*ngh 54

更新

你可以用它@ViewChildren来实现这个目的

有三种情况

1.ngFor由于ngIfon或它的父元素,初始化元素不是rendred

  • 在这种情况下,当ngIf您变得真实时,您将收到ViewChildren订阅通知

2. 初始化ngFor元素是rendred,无论是ngIf它还是它的父元素

  • 在这种情况下,ViewChildren订阅将不会第一次通知您,但您可以确定它是在ngAfterViewInit钩子中呈现

3.ngFor数组中添加/删除项目

  • 在这种情况下,ViewChildren订阅也会通知您

[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');
  }
}
Run Code Online (Sandbox Code Playgroud)

.


原版的

你可以这样做(但请看自己的副作用)

<ul>
  <li *ngFor="let i of items; let last = last">{{i}} {{last ? callFunction(i) : ''}}</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

哪个是无用的,除非与changeDetectionStrategy.OnPush一起使用

然后,您可以控制更改检测发生的次数,从而控制调用函数的次数.

即:你可以触发下一changeDetection时的数据items变化,你的函数将给予,适当的指示ngFor呈现了真正的变化.


Met*_*ian 5

我使用了一些其他人抱怨的方法的小技巧,它的作用就像一个魅力:

<ul>
  <li *ngFor="let i of items; let last = last">{{i}} {{last ? callFunction(i) : ''}}</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

然后在您的组件中:

shouldDoIt = true; // initialize it to true for the first run

callFunction(stuff) {
    if (this.shouldDoIt) {
        // Do all the things with the stuff
        this.shouldDoIt = false; // set it to false until you need to trigger again
    }
}
Run Code Online (Sandbox Code Playgroud)

这并没有解决这种方法的问题根源,但它是一种成本极低的黑客,使我的应用程序运行顺利。我确实希望 Angular 团队能够实现一种更友好的方式来在 *ngFor 加载其内容后触发一些代码。


Par*_*ain 3

您可以通过使用#lastof获取最后一个索引来执行相同的*ngFor操作,并通过获取最后一个索引值调用函数来完成您想要的任何操作。这是相同的代码 -

<ul>
   <li *ngFor="#item of items; #last = last">
    <span *ngIf='last'>{{hello(last)}}</span>
    {{item}}
   </li>
  </ul>


items: Array<number> = [1,2,3,4,5]
  constructor() { console.clear();}
  hello(a){
    if(a==true)
      this.callbackFunction();
  }
  callbackFunction(){
    console.log("last element");
  }
Run Code Online (Sandbox Code Playgroud)

相同的工作示例Working Plunker