微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

angualr4生命周期钩子

  1. 理解
    Angular提供了生命周期钩子,把这些关键生命时刻暴露出来,赋予我们在它们发生时采取行动的能力。可以将钩子函数理解为在合适的时候做合适的事情。
  2. 钩子函数
    ng4主要提供了8个钩子函数:
    ngOnchanges

    @input属性(输入属性)发生变化时,会调用。非此属性,不会调用。
       当输入属性为对象时,当对象的属性值发生变化时,不会调用,当对象的引用变化时会触发。
       先于ngOnInit调用

    ngOnInit

    只执行一次,dom操作可放在其中。(最常用)

    NgDocheck

    每次发生变更检测时会被调用
       ngDoCheck() 是Angular中的变更检测机制.它由 zone.js 来实现的.其行为是只要你的Angular中的某个组件发生异步事件.就会检查整个组件树,以保证组件属性的变化或页面的变化是同步的.所以 ngDoCheck() 的触发相当频繁的.并且是我们无法预料到的.也许我们在页面上的一个无意识操作,就会触发几个甚至几十个的 ngDoCheck() 生命周期钩子.

    ngAfterContentinit

    在组件内容初始化之后调用

    ngAfterContentChecked

    内容投影:父组件写在子标签间的内容会被渲染到子模板的ng-content中去,类似vue的slot
       组件及子组件每次检查内容调用
       当父子组件都有该钩子时,父组件先执行。

    ngAfterViewInt

    组件相应的视图初始化之后调用

    ngAfterViewChecked

    组件及子组件每次检查视图时调用
       当父子组件都有该钩子时,子组件先执行。
       ngAfterViewChecked与ngAfterViewInt中不允许修改绑定的属性(@input属性),否则抛出异常

    ngOnDestory

    销毁,事件解绑。

    3.执行顺序
    父组件:

组件模板
<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")
  }
}

子组件

@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。

原文地址:https://www.jb51.cc/angularjs/146262.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐