What's the difference between ngOnInit and ngAfterViewInit of Angular2?
Solution 1:
ngOnInit()
is called after ngOnChanges()
was called the first time. ngOnChanges()
is called every time inputs are updated by change detection.
ngAfterViewInit()
is called after the view is initially rendered. This is why @ViewChild()
depends on it. You can't access view members before they are rendered.
Solution 2:
ngOnInit()
is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated.
ngAfterViewInit()
is called after a component's view, and its children's views, are created. Its a lifecycle hook that is called after a component's view has been fully initialized.