Detailed explanation of the life cycle of Angular components (Part 2)

Detailed explanation of the life cycle of Angular components (Part 2)

1. View hook

There are two view hooks, ngAfterViewInit and ngAfterViewChecked.

1. Things to note when implementing ngAfterViewInit and ngAfterViewChecked hooks

Based on the example in Parent component calls child component method, implement the ngAfterViewInit and ngAfterViewChecked hooks in the parent component.

These two hook methods will be called after all the content of the component template is assembled and the component template has been presented to the user.

@ViewChild('child1')
child1:Child1Component; //Get the reference of the child component in the parent component ngOnInit(){
  this.child1.greeting("Tom");
}

ngAfterViewInit(){
  console.log("The parent component's view is initialized");
}

ngAfterViewChecked(){
  console.log("Parent component view change detection completed");
}

Also implement these two hooks in the child component

export class Child1Component implements OnInit,AfterViewInit,AfterViewChecked{

  constructor() { }

  ngOnInit() {
  }

  greeting(name: string) {
    console.log("hello" + name);
  }

  ngAfterViewInit(){
    console.log("The subcomponent's view has been initialized");
  }
  
  ngAfterViewChecked(){
    console.log("Subcomponent view change detection completed");
  }
}

In the ngOnInit of the parent component, the greeting() method of the child component is not called directly. Instead, it is called every 5 seconds through a timer.

ngOnInit(){
  setInterval(()=>{
    this.child1.greeting("Tom");
  },5000);
} 

Summarize:

1. Init is called first, then checked

In 1, first the subcomponent view is initialized, and then the subcomponent view change detection is completed.

2. Subcomponents are assembled before parent components

In 2, because two subcomponents are declared in the parent component, we can see that there are two subcomponent initialization actions. After subcomponent No. 1 is initialized and change detection is completed, subcomponent No. 2 is initialized and change detection is completed. The parent component's initialization is completed before it will be called, and then the parent component's change detection is completed before it will be called.

3. ngAfterViewInit will only be called once after initialization is completed.

4. After the timer triggers the method, the change detection of the two child components will be called, and the change detection of the parent component will also be called.

Even if the view has not changed, change detection will be called, and all methods implemented in the ngAfterViewChecked() hook will be called.

Therefore, the ngAfterViewChecked() hook must be concise to avoid performance issues.

2. Prohibit updating a view after it is assembled in a change detection cycle

example:

Parent Component

There is a message initialized to abc. and displayed on the template.

message:string='abc';

Change the message value in ngAfterViewInit of the parent component.

ngAfterViewInit(){
  console.log("The parent component's view is initialized");
  this.message="def";
} 

An error will be reported. Both ngAfterViewInit() and ngAfterViewChecked() are triggered after the view is assembled, so if the bound properties in the component are updated in these two hooks, triggering changes in the component view, Angular will throw an exception.

Solution:

Put the code inside another time loop.

ngAfterViewInit(){
  console.log("The parent component's view is initialized");
  setTimeout(()=>{
    this.message="def";
  },0);
}

2. Content hook

Includes 2 projection-related hooks, ngAfterContentInit() and ngAfterContentChecked() hooks.

ngAfterContentInit, ngAfterContentChecked are similar to ngAfterViewInit, ngAfterViewChecked.

ngAfterViewInit and ngAfterViewChecked are called after the entire component's view is assembled.

ngAfterContentInit and ngAfterContentChecked are called after the projected content is assembled.

1. Example of calling order of Content hook

Implement ngAfterContentInit, ngAfterContentChecked, and ngAfterContentInit() in the parent component

export class AppComponent implements OnInit, AfterViewInit, AfterContentInit, AfterContentChecked{

ngAfterViewInit(){
  console.log("The parent component's view is initialized");
}

ngAfterContentInit(){
  console.log("Parent component projection content initialization completed");
}
ngAfterContentChecked(){
  console.log("Parent component projection content change detection completed");
}

These three interfaces are also implemented in the subcomponent

export class Child2Component implements OnInit,AfterViewChecked,AfterContentInit,AfterContentChecked{

  constructor() { }

  ngOnInit() {
  }
  ngAfterViewInit(){
    console.log("The subcomponent's view has been initialized");
  }
  
  ngAfterContentInit(){
    console.log("Subcomponent projection content initialization completed");
  }
  ngAfterContentChecked(){
    console.log("Subcomponent projection content change detection completed");
  }
} 

When assembling the view, assemble the projected content first, then assemble the content of the view in the child component, and then add the content of the parent component itself, and then the parent component view is initialized.

2. Template content can be modified in the Content hook

The template content cannot be modified in the view hook because the content inside the template cannot be modified after it is assembled. But it is possible in the Content hook.

Because the entire view has not been assembled when the Content hook is called, only the projected content has been assembled.

No error will be reported if the message information is modified in the ngAfterContentInit hook in the parent component.

export class AppComponent implements OnInit, AfterViewInit, AfterContentInit, AfterContentChecked{
message:string='abc';
ngAfterViewInit(){
  console.log("The parent component's view is initialized");
}

ngAfterContentInit(){
  console.log("Parent component projection content initialization completed");
  this.message='def';
}
ngAfterContentChecked(){
  console.log("Parent component projection content change detection completed");
}
ngOnInit(){

} 

Conclusion

The above four methods are in the attribute initialization stage: the constructor initializes the object, ngOnChanges initializes the input attributes, ngOnInit initializes all attributes except the input attributes, and ngDoCheck performs a change check.

These four methods are executed until all properties of the entire component are assigned the values ​​they should be assigned.

The component starts rendering its view, first rendering the projected content, and then calling the ngAfterContentInit and ngAfterContentChecked hook methods.

If there are subcomponents, the process of subcomponent creation will be called. After the subcomponent is created or there is no subcomponent, the ngAfterViewInit and ngAfterViewChecked hook methods will be called after the view of the entire component is initialized.

At this point, the entire component is initialized and the component will be presented to the user for interaction.

User interaction triggers Angular's change detection mechanism. When a change is detected, all hook methods with check implemented on all active components in the current component tree will be called to check the changes of the current component. If the change causes the input property of a component to change, the ngOnChanges of that component will also be called.

When a component is destroyed due to a change in the routing address, ngOnDestory() will be called.

Destroy some referenced resources in ngOnDestory, such as unsubscribing a stream, clearing a timer, etc.

The above is the detailed explanation of the life cycle of Angular components (Part 2). For more information about Angular, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Several ways to implement angular component communication
  • Angular4 component communication methods (recommended)
  • Example code for extracting radio list of common components in Angular5
  • Angular dynamically adds components through instructions
  • Angular uses the dynamic loading component method to implement Dialog example
  • Example of how Angular packages and publishes components
  • Angular parent component calls child component method
  • Example code for interaction between Angular components

<<:  Solution - BASH: /HOME/JAVA/JDK1.8.0_221/BIN/JAVA: Insufficient permissions

>>:  Tutorial diagram of installing centos7.3 on vmware virtual machine

Recommend

How to install nginx under Linux

Nginx is developed in C language and is recommend...

Website redesign is a difficult task for every family

<br />Every family has its own problems, and...

How to connect XShell and network configuration in CentOS7

1. Linux network configuration Before configuring...

Vue implements multi-tab component

To see the effect directly, a right-click menu ha...

HTML form tag tutorial (1):

Forms are a major external form for implementing ...

How to Apply for Web Design Jobs

<br />Hello everyone! It’s my honor to chat ...

Detailed process of configuring NIS in Centos7

Table of contents principle Network environment p...

How to configure the same domain name for the front and back ends of nginx

This article mainly introduces the method of conf...

Detailed tutorial on deploying Apollo custom environment with docker-compose

Table of contents What is the Apollo Configuratio...

Tutorial on compiling and installing MySQL 5.7.17 from source code on Mac

1. Download and unzip to: /Users/xiechunping/Soft...

Detailed explanation of basic data types in mysql8.0.19

mysql basic data types Overview of common MySQL d...

jQuery realizes dynamic particle effect

This article shares the specific code of jQuery t...

Problems with installing mysql and mysql.sock under linux

Recently, I encountered many problems when instal...