Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
507 views
in Technique[技术] by (71.8m points)

javascript - execute a function when *ngFor finished in angular 2

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>

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Update

You can use @ViewChildren for that purpose

There are three cases

1. on initialization ngFor element is not rendred due to ngIf on it or it's parent

  • in which case, whenver ngIf becomes truthy, you will be notified by the ViewChildren subscription

2. on initialization ngFor element is rendred regardless of ngIf on it or it's parent

  • in which case ViewChildren subscription will not notify you for the first time, but you can be sure it's rendered in the ngAfterViewInit hook

3. items are added/removed to/from the ngFor Array

  • in which case also ViewChildren subscription will notify you

[Plunker Demo] (see console log there)

@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.ngForRendered();
    })
  }

  ngForRendered() {
    console.log('NgFor is Rendered');
  }
}

Original

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>

Which is Useless, unless used with changeDetectionStrategy.OnPush

Then you can have control over how many times change detection occurs, hence how many times your function is called.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...