Angular 中的生命周期钩子

Angel给了我们8个钩子,让我们可以进入组件的生命周期,并在生命周期中的特定时间点触发操作。

<$>[注]这篇文章讨论了角度2及以上的生命周期钩子。<$>

以下是可用的生命周期挂钩,按调用顺序排列:

  • ngOnChanges:每次数据绑定输入属性更改时调用。它是在 ngOnInit** 挂钩之前第一次调用的。该挂钩接收一个SimpleChanges对象,该对象包含数据绑定输入属性的前前值和当前值。这个钩子经常被调用,所以限制它的处理量是个好主意。
  • ngOnInit:组件初始化时调用一次。
  • ngDoCheck:对于角度未检测到的更改,请使用该钩子,而不是 ngOnChanges** 。它在每个更改检测周期都会被调用,因此将它所做的事情保持在最低限度对于性能来说很重要。
  • ngAfterContent Init:在Content is projectedin the Component]之后调用。
  • ngAfterContent Checked:检查投影内容后调用。
  • ngAfterViewInit:在组件的视图或子视图初始化后调用。
  • ngAfterViewChecked:在选中组件的视图或子视图后调用。
  • ngOnDestroy:在组件被销毁时调用一次,是用于清理和取消订阅可观察对象的良好挂钩。

ngOnInit

让我们给你一个使用ngOnInit钩子的简单例子。ngOnInit 生命周期钩子可能是您最常用的钩子。如果在创建组件时有大量的处理工作要做,最好在** ngOnInit** 钩子中而不是在构造函数中完成:

 1import { Component, OnInit } from '@angular/core';
 2
 3@Component({
 4  selector: 'my-app',
 5  templateUrl: './app.component.html'
 6})
 7export class AppComponent implements OnInit {
 8  constructor() {}
 9
10  ngOnInit() {
11    this.setupData();
12    this.doStuff();
13    // ...
14  }
15
16  setupData() {
17    // ...
18  }
19
20  doStuff() {
21    // ...
22  }
23}

注意我们如何导入OnInit,但我们使用ngOnInit方法实现它。其他生命周期钩子的原理也是如此。

多生命周期钩子

实现多个挂钩同样简单:

 1import { Component, OnInit, OnDestroy } from '@angular/core';
 2
 3@Component({
 4  selector: 'my-app',
 5  templateUrl: './app.component.html'
 6})
 7export class AppComponent implements OnInit, OnDestroy {
 8  constructor() {}
 9
10  ngOnInit() {
11    console.log('Component Init');
12  }
13
14  ngOnDestroy() {
15    console.log('Component Destroy');
16  }
17}

ngOnChanges

NgOnChanges挂钩与它的SimpleChanges对象略有不同。以下是您将如何实现它。假设我们有一个使用如下所示的组件:

1<my-todo [title]="title" [content]="content"></my-todo>

现在假设我们想要在标题属性更改时执行一些操作:

 1[label Child Component: my-todo.component.ts]
 2import { Component, Input, SimpleChanges, OnChanges }
 3  from '@angular/core';
 4
 5@Component({
 6  // ...
 7})
 8export class MyTodoComponent implements OnChanges {
 9  @Input() title: string;
10  @Input() content: string;
11  constructor() { }
Published At
Categories with 技术
Tagged with
comments powered by Disqus