Angular 2 Directive Lifecycle

风风火火
• 阅读 14757

在介绍 Angular 2 Directive Lifecycle (生命周期) 之前,我们先来介绍一下 Angular 2 中 Directive (指令) 与 Component (组件) 的关系。

Angular 2 Directive Lifecycle

我们再来看一下 Angular 2 中定义的指令和组件接口:

// angular2/packages/core/src/metadata/directives.ts

export interface Directive {
   selector?: string;  // 用于定义组件在HTML代码中匹配的标签
   inputs?: string[];  // 指令的输入属性
   outputs?: string[];  // 指令的输出属性
   host?: {[key: string]: string};  // 绑定宿主的属性、事件等
   providers?: Provider[];  // 设置指令及其子指令可以用的服务
   exportAs?: string;  // 导出指令,使得可以在模板中调用
   queries?: {[key: string]: any};  // 设置指令的查询条件
}

export interface Component extends Directive {
   changeDetection?: ChangeDetectionStrategy;  // 指定组件使用的变化检测策略
   viewProviders?: Provider[];     // 设置组件及其子组件(不含ContentChildren)可以用的服务
   moduleId?: string;  // 包含该组件模块的 id,它被用于解析 模版和样式的相对路径
   templateUrl?: string;  // 为组件指定一个外部模板的URL地址
   template?: string;  // 为组件指定一个内联的模板
   styleUrls?: string[];  // 为组件指定一系列用于该组件的样式表文件
   styles?: string[];  // 为组件指定内联样式
   animations?: any[];  // 设置组件相关动画
   encapsulation?: ViewEncapsulation;  // 设置组件视图包装选项
   interpolation?: [string, string];  // 设置默认的插值运算符,默认是"{{"和"}}"
   entryComponents?: Array<Type<any>|any[]>;  // 设置需要被提前编译的组件
}

通过观察上图与 Angular 2 中指令与组件的接口定义,我们可以总结出指令与组件之间的关系:组件继承于指令,并扩展了与 UI 视图相关的属性,如 template、styles、animations、encapsulation 等。

下面我们进入正题,开始介绍 Angular 2 指令的生命周期,它是用来记录指令从创建、应用及销毁的过程。Angular 2 提供了一系列与指令生命周期相关的钩子,便于我们监控指令生命周期的变化,并执行相关的操作。Angular 2 中所有的钩子如下图所示:

Angular 2 Directive Lifecycle

怎么那么多钩子,是不是被吓到了,没事我们基于指令与组件的区别来分个类:

  • 指令与组件共有的钩子

    • ngOnChanges

    • ngOnInit

    • ngDoCheck

    • ngOnDestroy

  • 组件特有的钩子

    • ngAfterContentInit

    • ngAfterContentChecked

    • ngAfterViewInit

    • ngAfterViewChecked

Angular 2 指令生命周期钩子的作用及调用顺序

  1. ngOnChanges - 当数据绑定输入属性的值发生变化时调用

  2. ngOnInit - 在第一次 ngOnChanges 后调用

  3. ngDoCheck - 自定义的方法,用于检测和处理值的改变

  4. ngAfterContentInit - 在组件内容初始化之后调用

  5. ngAfterContentChecked - 组件每次检查内容时调用

  6. ngAfterViewInit - 组件相应的视图初始化之后调用

  7. ngAfterViewChecked - 组件每次检查视图时调用

  8. ngOnDestroy - 指令销毁前调用

Angular 2 指令生命周期钩子详解

在详细介绍指令生命周期钩子之前,我们先来介绍一下构造函数:

constructor

组件的构造函数会在所有的生命周期钩子之前被调用,它主要用于依赖注入或执行简单的数据初始化操作。

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'; // 执行初始化操作
  }
}

ngOnChanges

当数据绑定输入属性的值发生变化的时候,Angular 将会主动调用 ngOnChanges 方法。它会获得一个 SimpleChanges 对象,包含绑定属性的新值和旧值,它主要用于监测组件输入属性的变化。

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
    <h4>Welcome to Angular World</h4>
    <exe-child name="exe-child-component"></exe-child>
  `,
})
export class AppComponent { }

child.component.ts

import { Component, Input, SimpleChanges, OnChanges } from '@angular/core';

@Component({
    selector: 'exe-child',
    template: `
      <p>Child Component</p>  
      <p>{{ name }}</p>
    `
})
export class ChildComponent implements OnChanges{
    @Input()
    name: string;

    ngOnChanges(changes: SimpleChanges) {
        console.dir(changes);
    }
}

以上代码运行后,浏览器的输出结果:

Angular 2 Directive Lifecycle

ngOnInit

在第一次 ngOnChanges 执行之后调用,并且只被调用一次。它主要用于执行组件的其它初始化操作或获取组件输入的属性值。

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值
    }
}

ngOnDestory

在指令被销毁前,将会调用 ngOnDestory 方法。它主要用于执行一些清理操作,比如:移除事件监听、清除定时器、退订 Observable 等。

@Directive({
    selector: '[destroyDirective]'
})
export class OnDestroyDirective implements OnDestroy {
  sayHello: number;
  
  constructor() {
    this.sayHiya = window.setInterval(() => console.log('hello'), 1000);
  }
  
  ngOnDestroy() {
     window.clearInterval(this.sayHiya);
  }
}

ngDoCheck

当组件的输入属性发生变化时,将会触发 ngDoCheck 方法。我们可以使用该方法,自定义我们的检测逻辑。它也可以用来加速我们变化检测的速度。

ngAfterContentInit

在组件使用 ng-content 指令的情况下,Angular 会在将外部内容放到视图后用。它主要用于获取通过 @ContentChild 或 @ContentChildren 属性装饰器查询的内容视图元素。

具体使用示例,请参考 - Angular 2 ContentChild & ContentChildren

ngAfterContentChecked

在组件使用 ng-content 指令的情况下,Angular 会在检测到外部内容的绑定或者每次变化的时候调用。

ngAfterViewInit

在组件相应的视图初始化之后调用,它主要用于获取通过 @ViewChild 或 @ViewChildren 属性装饰器查询的视图元素。

具体使用示例,请参考 - Angular 2 ViewChild & ViewChildren

ngAfterViewChecked

组件每次检查视图时调用

Angular 2 LifecycleHooks 、SimpleChanges 等相关接口

LifecycleHooks 接口

export interface OnChanges { ngOnChanges(changes: SimpleChanges): void; }

export interface OnInit { ngOnInit(): void; }

export interface DoCheck { ngDoCheck(): void; }

export interface OnDestroy { ngOnDestroy(): void; }

export interface AfterContentInit { ngAfterContentInit(): void; }

export interface AfterContentChecked { ngAfterContentChecked(): void; }

export interface AfterViewInit { ngAfterViewInit(): void; }

export interface AfterViewChecked { ngAfterViewChecked(): void; }

SimpleChange

// 用于表示变化对象
export class SimpleChange {
  constructor(public previousValue: any, 
      public currentValue: any, 
      public firstChange: boolean) {}
      
  // 标识是否为首次变化
  isFirstChange(): boolean { return this.firstChange; }
}

SimpleChanges

export interface SimpleChanges { [propName: string]: SimpleChange; }

Angular 2 View 详解

在 Angular 2 中 View (视图) 由三个部分组成:

  • Elements - 元素

  • Bindings - 绑定

  • Events - 事件

Angular 2 TemplateRef & ViewContainerRef 这篇文章中,我们介绍了 Angular 2 支持的 View(视图) 类型:

  • Embedded Views - Template 模板元素

  • Host Views - Component 组件

接下来我们来分析一下组件对应的 Host Views,具体示例如下:

child.component.ts

import { Component, Input, SimpleChanges, OnChanges, AfterViewChecked } from '@angular/core';

@Component({
    selector: 'exe-child',
    template: `
      <p>Child Component</p>  
      <p>{{ name }}</p>
    `
})
export class ChildComponent implements OnChanges, AfterViewChecked{
    @Input()
    name: string;

    ngOnChanges(changes: SimpleChanges) {
        console.dir(changes);
        setTimeout(() => {
            this.name = 'exe-child-component-1'
        }, 0);
    }

    ngAfterViewChecked() {
        console.log('ngAfterViewChecked hook has been called');
    }
}

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
    <h4>Welcome to Angular World</h4>
    <exe-child name="exe-child-component"></exe-child>
  `,
})
export class AppComponent { }

以上代码运行后,浏览器的输出结果:

Angular 2 Directive Lifecycle

接下来我们来分析一下 ChildComponent 组件,先来看一下编译后的 component.ngfactory.js 文件。

ChildComponent/component.ngfactory.js 代码片段:

function View_ChildComponent0(viewUtils,parentView,parentIndex,parentElement) {
  var self = this;
  ...
  self._expr_7 = jit_CD_INIT_VALUE5;
}

/*
* 用于初始化模板内的元素
* ChildComponent - template
* <p>Child Component</p>  
* <p>{{ name }}</p>
*/
View_ChildComponent0.prototype.createInternal = function(rootSelector) {
  var self = this;
  var parentRenderNode = self.renderer.createViewRoot(self.parentElement);
  ...
  
  // (1) 创建p元素 - <p>Child Component</p>  
  self._el_1 = jit_createRenderElement6(self.renderer,parentRenderNode,
      'p', jit__object_Object_7,self.debug(1,1,6));
      
  // 创建文本元素,设置内容为 - 'Child Component'
  self._text_2 = self.renderer.createText(self._el_1,'Child Component',
      self.debug(2,1,9));
  
  // (2) 创建p元素 - <p>{{ name }}</p>
  self._el_4 = jit_createRenderElement6(self.renderer,parentRenderNode,
       'p', jit__object_Object_7,self.debug(4,2,6));
       
  self._text_5 = self.renderer.createText(self._el_4,'',self.debug(5,2,9));
  
  self.init(null,(self.renderer.directRenderer? null: [...]
  ),null);
  return null;
};

// 执行变化检测                                                       
View_ChildComponent0.prototype.detectChangesInternal = function(throwOnChange) {
  var self = this;
  self.debug(5,2,9);
  var currVal_7 = jit_inlineInterpolate8(1,'',self.context.name,'');
  if (jit_checkBinding9(throwOnChange,self._expr_7,currVal_7)) {
    self.renderer.setText(self._text_5,currVal_7);
    self._expr_7 = currVal_7;
  }
};

ChildComponent/wrapper.ngfactory.js 代码片段:

function Wrapper_ChildComponent() {
  var self = this;
  self._changed = false;
  self._changes = {}; // 创建Changes对象
  self.context = new jit_ChildComponent0();
  self._expr_0 = jit_CD_INIT_VALUE1; // {}
}

Wrapper_ChildComponent.prototype.ngOnDestroy = function() { };

Wrapper_ChildComponent.prototype.check_name =function(currValue,
  throwOnChange, forceUpdate) {
  var self = this;
  // 判断值是否更新,jit_checkBinding2中直接使用looseIdentical(oldValue, newValue)
  // 进行全等比较(===)
  if ((forceUpdate || jit_checkBinding2(throwOnChange,self._expr_0,currValue))) {
    self._changed = true;
    self.context.name = currValue;
    // 创建name关联的SimpleChange对象
    self._changes['name'] = new jit_SimpleChange3(self._expr_0,currValue);
    self._expr_0 = currValue;
  }
};


Wrapper_ChildComponent.prototype.ngDoCheck = function(view,el,throwOnChange) {
  var self = this;
  var changed = self._changed;
  self._changed = false;
  if (!throwOnChange) { if (changed) {
    self.context.ngOnChanges(self._changes);
    jit_setBindingDebugInfoForChanges4(view.renderer,el,self._changes);
    self._changes = {};
  } }
  return changed;
};
 ...
return Wrapper_ChildComponent
})

我有话说

1.注册指令生命周期钩子时,一定要实现对应的接口么 ?

注册指令生命周期钩子时,实现对应的接口不是必须的,接口可以帮助我们在开发阶段尽早地发现错误,因为我们有可能在注册生命周期钩子的时候,写错了某个钩子的名称,在运行时可能不会抛出任何异常,但页面显示却不是预期的效果,因此建议读者还是遵守该开发规范。另外还要注意的一点是,TypeScript 中定义的接口,是不会编译生成 ES5 相关代码,它只用于编译阶段做校验。

未完待续

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
美凌格栋栋酱 美凌格栋栋酱
6个月前
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Jacquelyn38 Jacquelyn38
4年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Wesley13 Wesley13
3年前
FLV文件格式
1.        FLV文件对齐方式FLV文件以大端对齐方式存放多字节整型。如存放数字无符号16位的数字300(0x012C),那么在FLV文件中存放的顺序是:|0x01|0x2C|。如果是无符号32位数字300(0x0000012C),那么在FLV文件中的存放顺序是:|0x00|0x00|0x00|0x01|0x2C。2.  
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
PHP创建多级树型结构
<!lang:php<?php$areaarray(array('id'1,'pid'0,'name''中国'),array('id'5,'pid'0,'name''美国'),array('id'2,'pid'1,'name''吉林'),array('id'4,'pid'2,'n
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Python进阶者 Python进阶者
1年前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这
风风火火
风风火火
Lv1
你所见即我,好与坏都不反驳。
文章
5
粉丝
0
获赞
0