Angular 2 应用的生命周期需要经过一个多级的启动过程,我们可以在 App 启动、运行与创建/销毁组件的过程中响应大家的事件。

启动

Angular 2 应用需要通过应用的 根组件 (root component) 启动,在我们的主 JS 文件中,我们可以像下面这样写:

import {Component, bootstrap} from 'angular2/angular2'

// 注解部分
@Component({
  selector: 'my-app',
  template: '<h1>你好,{{ name }}</h1>'
})
// 组件控制器
class MyApp {
  constructor() {
    this.name = '潘韬'
  }
}

bootstrap(MyApp)

该代码片段中,你可以添加应用级别的代码与配置等,它的模板将是其它所有组件的容器。

组件初始化

当一个组件创建成功之后,它的构建函数 (constructor) 将被调用,在该函数中,你可以执行组件状态的初始化工作,但是如果应用依赖子组件的属性与数据的话,那么需要先等待子组件先完成初始化。要实现这样的功能,只需要使用生命周期事件 ngOnInit 即可,我们可以在 constructor 中使用 setTimeout 来模拟出相似的效果。

import {Component, bootstrap} from 'angular2/angular2'

@Component({
  selector: 'street-map',
  template: '<map-window></map-window><map-controls></map-controls>'
})
class StreetMap {
  constructor() {
    this.name = '潘韬'
  }

  setMapWindow(mapWindow) {
    this.mapWindow = mapWindow;
  }

  setMapControls(mapControls) {
    this.mapControls = mapControls;
  }

  ngOnInit() {
    // Properties are resolved and things like
    // this.mapWindow and this.mapControls
    // had a chance to resolve from the
    // two child components <map-window> and <map-controls>
  }
}

组件的生命周期

就像 ngOnInit 一样,我们可以在一个组件的生命周期中跟踪多个事件,下面列举出了部分常见的事件,查看完整的 Angular 2 生命周期事件钩子,可以查看官方文档

import {Component} from 'angular2/angular2'

@Component({
  selector: 'street-map',
  template: '<map-window></map-window><map-controls></map-controls>'
})
class StreetMap {
  constructor() {
    this.name = '潘韬';
  }

  ngOnInit() {

  }

  ngOnDestroy() {

  }

  ngOnCheck() {

  }

  ngOnChanges(changes) {

  }

  ngAfterContentInit() {

  }

  ngAfterContentChecked() {

  }

  ngAfterViewInit() {

  }

  ngAfterViewChecked() {

  }
}

标签: angularjs, angular, angular 2.0

评论已关闭