本文共 2465 字,大约阅读时间需要 8 分钟。
Angular每个组件都存在一个生命周期,从创建,变更到销毁。Angular提供组件生命周期钩子,把这些关键时刻暴露出来,赋予在这些关键结点和组件进行交互的能力。
名称 | 调用时机 | 接口名称 | 范围 |
---|---|---|---|
ngOnChanges | 当被绑定的输入属性的值发生变化时调用,首次调用一定会发生在 ngOnInit之前。 | OnChanges | 指令和组件 |
ngOnInit | 在第一轮 ngOnChanges 完成之后调用。 ( 译注:也就是说当每个输入属性的值都被触发了一次 ngOnChanges 之后才会调用 ngOnInit ,此时所有输入属性都已经有了正确的初始绑定值 ) | OnInit | 指令和组件 |
ngDoCheck | 在每个 Angular 变更检测周期中调用。 | DoCheck | 指令和组件 |
ngAfterContentInit | 当把内容投影进组件之后调用。 | AfterContentInit | 组件 |
ngAfterContentChecked | 每次完成被投影组件内容的变更检测之后调用。 | AfterContentChecked | 组件 |
ngAfterViewInit | 初始化完组件视图及其子视图之后调用。after initializing the component’s views and child views. | AfterViewInit | 组件 |
ngAfterViewChecked | 每次做完组件视图和子视图的变更检测之后调用。 | AfterViewChecked | 组件 |
ngOnDestroy | 当 Angular 每次销毁指令 / 组件之前调用。 | OnDestroy | 指令和组件 |
//在app.component.html代码
//在app.component.ts代码import { Component } from '@angular/core';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { name:any = "";}
//在life.component.html代码我是life组件
我是从父组件输入的内容:{
{ item}}
//在life.component.ts代码import { Component, OnInit,Input,OnChanges,SimpleChanges,DoCheck,AfterContentInit,AfterContentChecked,AfterViewInit,AfterViewChecked,OnDestroy} from '@angular/core';@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() item:any = ""; index:number = 0; log(arg):void{ console.log(`#${this.index}我是${arg}内容`); this.index ++; } constructor() { this.log("constructor"); } ngOnInit() { this.log("ngOnInit"); } ngOnChanges(changes:SimpleChanges){ this.log("ngOnChanges"); } ngDoCheck(){ this.log("ngDoCheck"); } ngAfterContentInit(){ this.log("ngAfterContentInit"); } ngAfterContentChecked(){ this.log("ngAfterContentChecked"); } ngAfterViewInit(){ this.log("ngAfterViewInit"); } ngAfterViewChecked(){ this.log("ngAfterViewChecked"); } ngOnDestroy(){ this.log("ngOnDestroy"); }}
1、项目初始化后运行效果如下:
2、当用户在输入框输入的时候,传递数据到子组件中运行效果如下:
angular
中变化检测的钩子函数有ngOnChanges、ngDocheck、ngAfterContentChecked、ngAfterViewChecked
ngOnChanges
的介绍ngOnChanges
钩子函数,把上面的代码修改下直接打印输出值ngOnChanges(changes:SimpleChanges){ console.log(JSON.stringify(changes,null,2)); }
运行输出结果,会展示一个对象,显示当前值与上一次的值