OverviewComponent declaration cycle and angular's change discovery mechanism The red method is executed only once. The green method executed during change detection is the same as the green method executed during component initialization. There are 9 methods in total. Each hook is an interface defined in the @angular/core library. import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-life', templateUrl: './life.component.html', styleUrls: ['./life.component.css'] }) export class LifeComponent implements OnInit { constructor() { } ngOnInit() { } } Although the interface is not required, Angular will execute it when it detects the hook method, so it is recommended to write the interface. 1. Hook calling orderimport { Component, OnInit, OnChanges, DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked, OnDestroy, Input, SimpleChange, SimpleChanges } from '@angular/core'; let logIndex: number = 1; //Counter@Component({ selector: 'app-life', templateUrl: './life.component.html', styleUrls: ['./life.component.css'] }) export class LifeComponent implements OnInit, OnChanges, DoCheck, AfterContentInit , AfterContentChecked, AfterViewInit, AfterViewChecked, OnDestroy { @Input() name: string; logIt(msg: string) { console.log(`# ${logIndex++} ${msg}`); } constructor() { this.logIt("The value of the name property in the constructor is: " + this.name); } ngOnInit() { this.logIt("The value of the name property in OnInit is: " + this.name); } ngOnChanges(changes: SimpleChanges): void { // Pass in a SimpleChanges object let name = changes['name'].currentValue; this.logIt("The value of the name attribute in ngOnChanges is: " + this.name); } ngDoCheck(): void { this.logIt("DoCheck"); } ngAfterContentInit() { this.logIt("ngAfterContentInit"); } ngAfterContentChecked() { this.logIt("ngAfterContentChecked"); } ngAfterViewInit() { this.logIt("ngAfterViewInit"); } ngAfterViewChecked() { this.logIt("ngAfterViewChecked"); } ngOnDestroy() { this.logIt("ngOnDestory"); } } When the initialization logic depends on the value of an input property, the initialization logic must be written in ngOnInit and not in the constructor. DoCheck is called during every change detection cycle in Angular. ngAfterContentInit and ngAfterContentChecked are related to templates and component content projection. ngAfterViewInit and ngAfterViewChecked are related to the component template and initialization view. 2. onChanges hookThe parent component is called when it initializes or modifies the input parameters of the child component. You need to understand mutable objects and immutable objects in js first. //Strings are immutable var greeting = "Hello"; greeting = "Hello World"; //Objects are mutable var user = { name: "Tom" }; user.name = "Jerry"; example: The child component has 3 properties, 2 of which are input properties. The parent component has a greeting property and a name property which is Tom's user object. The parent component wants to change the input property, so greeting and user.name are two-way bound. <div class="parent"> <h2>I am the parent component</h2> <div>Greeting: <input type="text" [(ngModel)]="greeting"></div> <div> Name: <input type="text" [(ngModel)]="user.name"> </div> <app-child [greeting]="greeting" [(user)]="user"> </app-child> </div> When the parent component changes the values of the two inputs, the values passed into the child component will also change. When the values of the input properties passed into the child component change, ngOnChanges() will be triggered. The parent component initializes the child component. Call ngOnChanges() once during initialization. After initialization, the greeting of the child component becomes Hello, which is the value of the greeting on the parent component. user becomes an object with a name attribute of Tom. Change the value of the input attribute and change the parent component greeting to Helloa. Angular's change detection refreshes the immutable object, that is, the value of greeting, and then calls the ngOnChanges() method. The value of greeting changes from the previous hello to Helloa. Change user.name to Tomb, and no new messages are printed on the console. Because the user only changed the properties of the mutable object user, the reference to the user object itself did not change, so the onChanges() method was not called. Although the property changes of the mutable object will not trigger the ngOnChanges() method call, the properties of the child component's user object are still changed, because Angular's change detection mechanism still captures the property changes of each object in the component. Changing the message property of a child component does not cause the child component's onChanges() method to be called. Because message is not an input attribute. ngOnChanges() is called only when the input property changes. 3. Change Detection Mechanism and DoCheck() HookChange detection is implemented by zone.js. Ensure that component property changes are synchronized with page changes. Asynchronous events that occur in the browser (clicking a button, entering data, data coming back from the server, calling the setTimeout() method) will trigger change detection. When change detection is running, all binding relationships on the component template are detected. If the component properties are changed, the corresponding area of the template bound to it may need to be updated. Note: The change detection mechanism only reflects changes in component properties to the template. The change detection mechanism itself will never change the value of component properties. Two change detection strategies.
An Angular application is a component tree with the main component as its root. Each component generates a change detector. When any change detector detects a change, zone.js checks the component based on the component's change check strategy (that is, calls the doCheck() hook) to determine whether the component needs to update its template. DoCheck checks all component trees starting from the root component, regardless of which component the change occurs in. example: Monitor changes to attributes of mutable objects such as user.name. Add an oldUsername in child to store the username before the change, and add a changeDetected attribute to mark whether the username has changed. The default value is false. The noChangeCount counter defaults to 0. import { Component, OnInit, Input, OnChanges, SimpleChanges, DoCheck } from '@angular/core'; @Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.css'] }) export class ChildComponent implements OnInit, OnChanges, DoCheck { @Input() greeting: string; @Input() user: { name: string }; message: string = "Initialization message"; oldUsername: string; changeDetected: boolean = false; noChangeCount: number = 0; constructor() { } ngOnInit() { } ngOnChanges(changes: SimpleChanges): void { console.log(JSON.stringify(changes, null, 2)); } ngDoCheck() { if (this.user.name !== this.oldUsername) { this.changeDetected = true; console.log("DoCheck: user.name changes from " + this.oldUsername + " to " + this.user.name); this.oldUsername = this.user.name; } if (this.changeDetected) {//Change counter cleared to 0 this.noChangeCount = 0; } else {//No change this.noChangeCount++; console.log("DoCheck: ngDoCheck method has been called when user.name has not changed" + this.noChangeCount + "times") } this.changeDetected = false; //Finally, the flag is reset regardless of whether it has changed or not} } Page loading completed: DoCheck method has been called once when user.name has not changed. Mouse clicks do not change any values. Clicking triggers the change detection mechanism, and DoCheck of all components will be called. Change Tom to Tomb, and DoCheck will detect that Tom has changed to Tomb. Although the DoCheck() hook can detect when user.name changes, it must be used with caution because the ngDoCheck() hook is called very frequently. This is called after every change detection cycle when changes occur. The implementation of ngDoCheck() must be very efficient and lightweight, otherwise it is easy to cause performance problems. Similarly: all hook methods with the Check keyword must be used with great caution. ngDoCheck,ngAfterContentChecked,ngAfterViewChecked. The above is the detailed explanation of the Angular component life cycle (Part 1). For more information about the Angular component life cycle, please pay attention to other related articles on 123WORDPRESS.COM! You may also be interested in:
|
<<: Complete steps to build a Laravel development environment using Docker
Vue $set array collection object assignment In th...
Table of contents 1. Pull the image 2. Create a R...
Table of contents 1. Add attributes 2. Merge mult...
Table of contents Nesting Parent-child component ...
Find the problem Today at work, when copying tabl...
This article describes the VMware virtual machine...
Recently, I have used React Hooks in combination ...
Table of contents 1. Introduction 2. Aggregation ...
React is a JavaScript library for building user i...
In the process of writing the project page, I enc...
Nested use of MySQL ifnull I searched online to s...
This article describes how to use docker to deplo...
1. Docker pull pulls the image When using $ docke...
Lists for organizing data After learning so many ...
Where is my hometown when I look northwest? How m...