export class LifecircleComponent { constructor() { console.log('00构造函数执行了---除了使用简单的值对局部变量进行初始化以外,什么都不该该作') } ngOnChanges() { console.log('01ngOnChages执行了---当被绑定的输入属性的值发生变化时调用(父子组件传值的时候会触发)'); } ngOnInit() { console.log('02ngOnInit执行了--- 请求数据通常放在这个里面'); } ngDoCheck() { console.log('03ngDoCheck执行了---检测,并在发生 Angular 没法或不肯意本身检测的变化时做出反应'); } ngAfterContentInit() { console.log('04ngAfterContentInit执行了---当把内容投影进组件以后调用'); } ngAfterContentChecked() { console.log('05ngAfterContentChecked执行了---每次完成被投影组件内容的变动检测以后调用'); } ngAfterViewInit() : void { console.log('06 ngAfterViewInit执行了----初始化完组件视图及其子视图以后调用(dom操做放在这个里面)'); } ngAfterViewChecked() { console.log('07ngAfterViewChecked执行了----每次作完组件视图和子视图的变动检测以后调用'); } ngOnDestroy() { console.log('08ngOnDestroy执行了····'); } //自定义方法 changeMsg() { this.msg = "数据改变了"; } }
import { Component, ElementRef } from '@angular/core'; @Component({ selector: 'my-app', template: ` <h1>Welcome to Angular World</h1> <p>Hello {{name}}</p> `, }) export class AppComponent { name: string = ''; constructor(public elementRef: ElementRef) {//使用构造注入的方式注入依赖对象 // 执行初始化操做 this.name = 'Semlinker'; } }
// 父组件中 传递title属性给header子组件 <app-header [title]="title"></app-header>
此时改变title会触发ngOnChanges生命周期,而且也会触发
安全
在 Angular 第一次显示数据绑定和设置指令/组件的输入属性以后,初始化指令/组件。在第一轮 ngOnChanges() 完成以后调用,只调用一次。能够请求数据app
import { Component, Input, OnInit } from '@angular/core'; @Component({ selector: 'exe-child', template: ` <p>父组件的名称:{{pname}} </p> ` }) export class ChildComponent implements OnInit { @Input() pname: string; // 父组件的名称 constructor() { console.log('ChildComponent constructor', this.pname); // Output:undefined } ngOnInit() { console.log('ChildComponent ngOnInit', this.pname); // output: 输入的pname值 } }