The life cycle

Angular generates a series of hook functions when it instantiates a component. These hook functions represent the process of generating, changing, and destroying a component. This process is called the lifecycle. Common life cycles: component creation, component content update, component destruction.

constructor

Where the constructor class initializes the component, which typically deals with data initialization, service dependency injection, and so on, the Input properties of the @Input configuration cannot be obtained.

ngOnChanges

Listen for changes in the data passed from the parent to the child, the first time passed before ngOnInit.

@Input() info: string;
ngOnChanges(changes: SimpleChanges): void {
    // Structure the info data. Only info data is processed here
    (({info}) = > {
        console.log(info.previousValue,info.currentValue);
    })(changes);
}
Copy the code

Note: If the input property is an object and one of the properties of the object changes but the address does not change, this hook function does not fire. You can use the ngDoCheck hook, which triggers change detection that Angular cannot detect. Although ngOnChanges is not triggered, the content view has been updated and the data obtained is up to date.

ngOnInit

Called only once, after Angular first displays the data binding and sets the input properties of a component or directive. This is usually where you get the data from the server.

ngAfterViewInit

Called only once after Angular has initialized the component view and its child views or views that contain the directive.

ngAfterViewChecked

Angular is called multiple times after detecting changes to component views and subviews or views that contain this directive. It is rarely used.

ngAfterContentInit

Called after Angular projects external content into the component view or directive’s view. The parent component:

<app-liftcycle> 
    <h1>Content of the projection</h1>
</app-liftcycle>
Copy the code

Child components:

<div>The child component receives the content projection in and out with ng-Content<ng-content></ng-content>
</div>
Copy the code

ngAfterContentChecked

Called whenever Angular checks what is projected into a component or directive.

ngOnDestroy

A hook function that is triggered before a component is destroyed. It is used to unsubscribe, clear timers, etc., to avoid memory leaks.