Angular之constructor和ngOnInit差异及适用场景
Angular中根据适用场景定义了很多生命周期函数,其本质上是事件的响应函数,其中最常用的就是 区别
import {Component} from '@angular/core';
@Component({
selector: 'hello-world',templateUrl: 'hello-world.html'
})
class HelloWorld {
constructor() {
console.log('constructor被调用,但和Angular无关');
}
}
// 生成类实例,此时会调用constructor
new HelloWorld();
既然Angular无法控制
import {Component,OnInit} from '@angular/core';
@Component({
selector: 'hello-world',templateUrl: 'hello-world.html'
})
class HelloWorld implements OnInit {
constructor() {
}
ngOnInit() {
console.log('ngOnInit被Angular调用');
}
}
constructor适用场景即使Angular定义了 import { Component,ElementRef } from '@angular/core';
@Component({
selector: 'hello-world',templateUrl: 'hello-world.html'
})
class HelloWorld {
constructor(private elementRef: ElementRef) {
// 在类中就可以使用this.elementRef了
}
}
在 ngOnInit适用场景
// hello-world.ts
import { Component,Input,OnInit } from '@angular/core';
@Component({
selector: 'hello-world',template: `<p>Hello {{name}}!</p>` }) class HelloWorld implements OnInit { @Input() name: string; constructor() { // constructor中还不能获取到组件/指令中被传入的数据 console.log(this.name); // undefined } ngOnInit() { // ngOnInit中已经能够获取到组件/指令中被传入的数据 console.log(this.name); // 传入的数据 } }
所以我们可以在 总结开发中我们经常在 参考文档
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |