Skip to content

Angular 生命周期介绍 #59

Open
@deepthan

Description

@deepthan

component/directive都有生命周期(组件也是指令),下以组件举例说明

import { OnChanges, SimpleChanges, } from "@angular/core";

1. 有哪些生命周期?

1.1 OnChanges

  • 调用时机:传到组件的值变化时调用(一般为@input接的数据)。

  • 参数SimpleChange;它是一个对象,有如下属性

    class SimpleChange {
      constructor(previousValue: any, currentValue: any, firstChange: boolean)
      previousValue: any // --> 变化之前的值
      currentValue: any // --> 变化之后的值
      firstChange: boolean // 是否为第一次变化
      isFirstChange(): boolean // 一个方法,返回是否为第一次变化,返回值和firstChange一样
    }
    
    SimpleChange使用示例
    @Input() title;
    ngOnChanges(simpleChange:SimpleChanges){
        // 判断是否存在方式报错
        if('title' in simpleChange){
           console.log("变化之前的值", simpleChange.title.previousValue)
           console.log("变化之后的值", simpleChange.title.currentValue)
        }
    }
  • 注意事项:若传过来的值为引用类型,引用发生变化才会调用这个生命周期。

1.2 OnInit

  • 调用时机:初始化组件后调用。只执行一次,这时视图还未渲染。
  • 注意事项:一般在这里做请求接口等初始化操作。

1.3 DoCheck

  • 调用时机
    • 只要有任何change detection(比如click handlers, http requests, route changes…)都会执行ngDoCheck;
    • 状态发生变化,angular自己又不能捕获这个变化会触发ngDoCheck。
  • 注意事项:这个生命周期触发的相当频繁,一般不建议使用。

1.4 AfterContentInit

  • 调用时机: 把外部内容投影进组件的视图之后调用,这里外部的内容指的是通过ng-content接收的内容。
  • 指令无此生命周期

1.5 AfterContentChecked

  • 调用时机:完成被投影组件内容的变更检测之后调用。
  • 指令无此生命周期

1.6 AfterViewInit

  • 调用时机:初始化完组件或其子组件视图后调用
  • 指令无此生命周期

1.7 AfterViewChecked

  • 调用时机:组件视图和子视图的变更检测之后调用
  • 指令无此生命周期

1.8 OnDestroy

  • 调用时机:销毁组件之前调用,一般在这里取消订阅、事件监听等以防内存泄漏。

2. FAQ

2.1 constructor 和 OnInit 有啥区别?

在constructor里并不是所有数据都已经存在,比如@ContentChildren/@ContentChild/@ViewChildren/@ViewChild/@Input在执行constructor的时候并不存在,相关代码最好都放在ngOnInit。

2.2 AfterContentInit 和 AfterViewInit 有啥不一样的?

AfterContentInitng-content投射过来的内容初始化完成调用。如果是想要对ng-content传递过来的操作可以使用它。
AfterViewInit是把组件、子组件的的其他内容初始化完成调用。如果想对页面操作可以使用它。

==不可以在AfterContentInit、AfterViewInit生命周期里去改变父组件的值!==

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions