钩子函数
ng4主要提供了8个钩子函数:
ngOnchangescss
@input属性(输入属性)发生变化时,会调用。非此属性,不会调用。 当输入属性为对象时,当对象的属性值发生变化时,不会调用,当对象的引用变化时会触发。 先于ngOnInit调用。
ngOnInithtml
只执行一次,dom操做可放在其中。(最经常使用)
NgDocheckvue
每次发生变动检测时会被调用 ngDoCheck() 是Angular中的变动检测机制.它由 zone.js 来实现的.其行为是只要你的Angular中的某个组件发生异步事件.就会检查整个组件树,以保证组件属性的变化或页面的变化是同步的.因此 ngDoCheck() 的触发至关频繁的.而且是咱们没法预料到的.也许咱们在页面上的一个无心识操做,就会触发几个甚至几十个的 ngDoCheck() 生命周期钩子.
ngAfterContentInitdom
在组件内容初始化以后调用
ngAfterContentChecked异步
内容投影:父组件写在子标签之间的内容会被渲染到子模板的ng-content中去,相似vue的slot 组件及子组件每次检查内容时调用 当父子组件都有该钩子时,父组件先执行。
ngAfterViewInt函数
组件相应的视图初始化以后调用
ngAfterViewCheckedspa
组件及子组件每次检查视图时调用 当父子组件都有该钩子时,子组件先执行。 ngAfterViewChecked与ngAfterViewInt中不容许修改绑定的属性(@input属性),不然抛出异常
ngOnDestorycode
销毁,事件解绑。
3.执行顺序
父组件:component
组件模板 <div class="panel-body"> <input type="text" [(ngModel)]="name"> {{name}} <son [name]="name"></son> </div> 组件 @Component({ selector: 'father', templateUrl: './father.component.html', styleUrls: ['./father.component.scss'] }) export class FatherComponent implements OnInit { public name:string; constructor() { } ngOnInit() { console.log("父组件ngOninit"); } ngOnchanges(){ console.log("父组件ngonchanges"); } ngDoCheck (){ console.log("父组件ngDocheck") } ngAfterContentInit(){ console.log("父组件ngAfterContentInit") } ngAfterContentChecked(){ console.log("父组件ngAfterContentChecked") } ngAfterViewInit(){ console.log("父组件ngAfterViewInit") } ngAfterViewChecked(){ console.log("父组件ngAfterViewChecked") } }
子组件htm
@Component({ selector: 'son', templateUrl: './son.component.html', styleUrls: ['./son.component.scss'] }) export class SonComponent implements OnInit { @Input() name:string; constructor() { } ngOnInit() { console.log("子组件ngOninit"); } ngOnChanges (){ console.log("子组件ngonchanges"); } ngDoCheck (){ console.log("子组件ngDocheck") } ngAfterContentInit(){ console.log("子组件ngAfterContentInit") } ngAfterContentChecked(){ console.log("子组件ngAfterContentChecked") } ngAfterViewInit(){ console.log("子组件ngAfterViewInit") } ngAfterViewChecked(){ console.log("子组件ngAfterViewChecked") } }
看打印结果:
当在父组件的input中输入内容时,会打印以下结果:
看到有人说只有当使用内容投影时才会调用ngAfterConentChecked,当上面的里面的代码很显然是没用ng-content的,不知道该怎么解释这个ngAfterConentChecked。