Angular ngFor lifecycle

前端 未结 2 578
醉酒成梦
醉酒成梦 2021-01-21 22:11

I\'m using *ngFor to iterate some data like this:

{{d}}

Everything is fine

2条回答
  •  日久生厌
    2021-01-21 22:49

    using methods in the view is the same that using impure pipes. This code will be executed in each event on the view, which can be a lot of times. In our example, the logAndReturn() method only returns a number so it can be assumable to run it in a view but if it would do something more complex, it could be a big problem of performance. with a simple program you can check console.log to see in which step the trace of “logAndReturn” is printed. This is the look of the new component:

    export class AppComponent implements 
    OnChanges,
    OnInit,
    DoCheck,
    AfterContentInit,
    AfterContentChecked,
    AfterViewInit,
    AfterViewChecked,
    OnDestroy
    {
      private var01: string = "default value";
      constructor( private trans: TranslatorService ){}
      ngOnChanges (){
         console.log('Trace OnChanges');
      }
      ngOnInit (){
         console.log('Trace onInit');
      }
      ngDoCheck (){
         console.log('Trace doCheck');
      }
      ngAfterContentInit(){
         console.log('Trace After Content Init');
      }
      ngAfterContentChecked(){
         console.log('Trace after contente checked');
      }
      ngAfterViewInit(){
         console.log('Trace after view init');
      }
      ngAfterViewChecked(){
         console.log('Trace after view checked');
      }
      ngOnDestroy(){
         console.log('Trace on destroy');
      }
      testRender() {
        console.log('trace 01');
        return 'This is a test that runs a console log'
      }
      (...)
    }
    

    To go deeper in what really is happening here, read the official documentation of Angular 2 about the life cycle

提交回复
热议问题