挂载阶段的生命周期函数只在挂载阶段执行一次,数据更新时不再执行
constructor
Angular 在实例化组件类时执行, 可以用来接收 Angular 注入的服务实例对象
export class HelloComponent {constructor(private test: TestService) {console.log(this.test) // "test"}}
ngOnInit
在首次接收到输入属性值后执行,在此处可以执行请求操作
export class HelloComponent implements OnInit {@Input("name") name: string = ""constructor() { }ngOnInit() {console.log(this.name) // "张三"}}
ngAfterContentInit
当内容投影初始渲染完成后调用 ```typescript
Hello Angular
export class ChildComponent implements AfterContentInit {
@ContentChild(“box”) box: ElementRef
ngAfterContentInit() {console.log(this.box) // <div>Hello Angular</div>}
}
<a name="s06XN"></a>### ngAfterViewInit- 当组件视图渲染完成后调用```typescript<!-- app-child 组件模板 --><p #p>app-child works</p>export class ChildComponent implements AfterViewInit {@ViewChild("p") p: ElementRef<HTMLParagraphElement> | undefinedngAfterViewInit () {console.log(this.p) // <p>app-child works</p>}}
