In Angular, every component has a life-cycle, a number of different stages it goes through.
- Creates the component
- Renders the component
- Creates and renders the component children
- Checks when the component data-bound properties change, and
- Destroys the component before removing it from the DOM
- ngOnChanges
this method is called once on component’s creation and then every time changes are detected in one of the component’s input properties.
export class MyComponent implements OnChanges { ngOnChanges(changes: SimpleChanges) {
// Insert Logic Here!
}}
- ngOnInit
Invoked when given component has been initialized.
This hook is only called once after the firstngOnChanges
export class MyComponent implements OnInit { ngOnInit() {
// Insert Logic Here!
}}- ngDoCheck
Invoked when the change detector of the given component is invoked. It allows us to implement our own change detection algorithm for the given component.
export class MyComponent implements DoCheck { ...
private _currentValue;
private _previousValue;
public changeDetected: boolean = false;
... ngDoCheck() {
if (this._previousValue !== this._currentValue) {
this.changeDetected = true;
// Insert Logic Here
}
}Important
ngDoCheck
andngOnChanges
should not be implemented together on the same component.
ngOnDestroyUse this hook to unsubscribe observables and detach event handlers to avoid memory leaks.
export class MyComponent implements OnDestroy { ngOnDestroy() {
// Insert Logic Here!
}}
Invoked after Angular performs any content projection into the component’s view.
export class MyComponent implements AfterContentInit { @ContentChild('content') content: ElementRef;
ngAfterContentInit() {
// Now we have access to 'this.content'!
// Insert Logic Here!
}
}- ngAfterContentChecked
Invoked each time the content of the given component has been checked by the change detection mechanism of Angular.
export class MyComponent implements AfterContentChecked { @ContentChild('content') content: ElementRef;
ngAfterContentChecked() {
// We have access to 'this.content'!
// Content has already been checked!
// Insert Logic Here!
}
}
- ngAfterViewInit
Invoked when the component’s view has been fully initialized.
export class MyComponent implements AfterViewInit { @ViewChild('wrapper') wrapper: ElementRef;
ngAfterViewInit() {
// Now we have access to 'this.wrapper'
// Insert Logic Here!
}
}
- ngAfterViewChecked
Invoked each time the view of the given component has been checked by the change detection mechanism of Angular.
export class MyComponent implements AfterViewChecked { @ViewChild('wrapper') wrapper: ElementRef;
ngAfterViewChecked() {
// Now we have access to 'this.wrapper'!
// View has already been checked!
// Insert Logic Here!
}
}
Comments
Post a Comment