Angular. Component lifecycle
Every Angular component has its own lifecycle. Lifecycle includes several optional methods, which you can realize for response to different component events (change detection run for example)
To describe lifecycle method (hooks) you need implement interface contains this method. There are several build-in Angular interfaces OnInit, OnChanges, DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked, OnDestroy. While realize interface in component class of course you need describe the interface method (see code example).
Code lesson (user.component.ts)
import {
AfterContentChecked,
AfterContentInit, AfterViewChecked, AfterViewInit,
ChangeDetectionStrategy,
Component,
DoCheck,
Input,
OnChanges, OnDestroy,
OnInit,
SimpleChanges
} from '@angular/core';
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class UserComponent implements OnInit, OnChanges, DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked, OnDestroy {
@Input() user: string = '';
fullName: string = '';
constructor() {
console.log(this);
}
ngOnChanges(changes: SimpleChanges): void {
console.log(changes);
}
ngOnInit(): void {
console.log('on init');
}
ngDoCheck() {
console.log('do check');
}
ngAfterContentInit() {
// console.log('call after content init');
}
ngAfterContentChecked() {
// console.log(this.user, this.fullName);
}
ngAfterViewInit() {
}
ngAfterViewChecked() {
}
ngOnDestroy() {
}
changeUser() {
// this.user = 'my user';
this.fullName = 'full name';
}
}
0 Comments