bootstrap
Angular2中,一个App需要用它的根组件进行引导
import {Component, bootstrap} from 'angular2/angular2';// Annotation section@Component({ selector: 'my-app', template: 'Hello { { name }}
'})// Component controllerclass MyApp { constructor() { this.name = 'Max'; }}bootstrap(MyApp)
你可以把应用程序的代码和配置文件放到这个组件中,并且整个应用程序的组件链将会在它的模板文件中被创建
初始化组件
当一个组件被创建的时候,它的构造器就会生效.我们就是在这个构造器里面初始化组件的状态.但是如果要用到子组件当中的属性或者数据的话,就需要先等待一段时间.(等父组件依赖的子组件被创建之后才能初始化父组件).
这种情况下,我们可以使用setTimeout来解决这个问题.但是在这里,我们推荐你用生命周期事件onInit:
import {Component, bootstrap, onInit} from 'angular2/angular2';// Annotation section@Component({ selector: 'street-map', template: '', lifecycle: [onInit]})// Component controllerclass StreetMap { constructor() { this.name = 'Max'; setTimeout(() => { // Similar to onInit below, but not recommended. // Could be useful in a pinch, though. }); } setMapWindow(mapWindow) { this.mapWindow = mapWindow; } setMapControls(mapControls) { this.mapControls = mapControls; } onInit() { // Properties are resolved and things like // this.mapWindow and this.mapControls // had a chance to resolve from the // two child components and }}
组件的生命周期
就像onInit,我们可以根据组件的生命周期追踪几个事件
import {..., onInit, onDestroy, onChange, onCheck, onAllChangesDone} from 'angular2/angular2';// Annotation section@Component({ selector: 'street-map', template: '', lifecycle: [onInit, onDestroy, onChange, onCheck, onAllChangesDone]})// Component controllerclass StreetMap { onInit() { // Properties are resolved and things like // this.mapWindow and this.mapControls // had a chance to resolve from the // two child components and } onDestroy() { // Speak now or forever hold your peace } onCheck() { // Called right after our bindings have been checked } onChange(changes) { // Called right after our bindings have been checked but only // if one of our bindings has changed. // // changes is an object of the format: // { // 'prop': PropertyUpdate // } } onAllChangesDone() { // Called right after all of our bindings have been checked }}