Skip to content

Instantly share code, notes, and snippets.

@ninadvadujkar
Last active May 28, 2018 07:10
Show Gist options
  • Save ninadvadujkar/36223249a5fc9b3b7b3cb2be01f082aa to your computer and use it in GitHub Desktop.
Save ninadvadujkar/36223249a5fc9b3b7b3cb2be01f082aa to your computer and use it in GitHub Desktop.
Text about Angular lifecycle hooks extracted from codecraft.tv Angular course
Lifecycle hooks Angular
constructor
ngOnChanges
ngOnInit
ngDoCheck
ngAfterContentInit
ngAfterContentChecked
ngAfterViewInit
ngAfterViewChecked
ngOnDestroy
1. constructor - invoked when Angular creates a component/directive by calling 'new' on the class
2. ngOnChanges - invoked 'everytime' there is a change in the 'input' properties of the component
3. ngOnInit - invoked when the component is being initialized. Called only 'once' after the first 'ngOnChanges'
4. ngDoCheck - invoked when CD(change detection) of the component in invoked. Allows us to implement our own CD algorithm for that component
NOTE - ngDoCheck and ngOnChanges should not be implemented together on the same component.
5. ngOnDestroy - invoked just before Angular destroys the component
Hooks for components' children-
NOTE - Only called for components and not directives
1. ngAfterContentInit - invoked after Angular performs any content-projection(ng-content) into the components' view.
2. ngAfterContentChecked - invoked 'each time' the content of the given component has been checked by the CD mechanism
3. ngAfterViewInit - invoked when components' view has been fully initialized
4. ngAfterViewChecked - invoked 'each time' the view of the component has been checked by the CD mechanism of Angular
-----------------------------------------------------------------------------------------------------------------------------
@ViewChild(), @ViewChildren() decorators can be used to get the reference of children'n view. @ViewChild() can also be used to get reference of a template variable in the component class.
@ViewChild() returns the first one that it finds. @ViewChildren() returns a QueryList of all the matched children references.
We can see the referenced child's view only in ngAfterViewInit(). It's not available before.
@ContentChild(), @ContentChildren() decorators can be used to get the reference of children that are projected into the component from the host component.
The lifecycle hook associated here is ngAfterContentInit()
Content children are only visible by the time AfterContentInit lifecycle hook has run.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment