目录constructor和nGoninit的使用区别适用场景ngOnInit函数学习小记例子constructor和ngOninit的使用 angular中根据适用场景定义了很多生
angular中根据适用场景定义了很多生命周期函数,其本质上是事件的响应函数,其中最常用的就是ngOnInit。在typescript或es6中还存在着名为constructor的构造函数,开发过程中经常会混淆二者,两者在含义上有部分重复,下面主要解析一下它们的区别和各自的使用场景。
constructor:Es6引入类的概念后出来的东西,是类自身的属性,并不属于angular,所以Angular没有办法控制constructor。
constructor会在类生成实例时调用:
import {Component} from '@angular/core';
@Component({
selector: 'hello-world',
templateUrl: 'hello-world.html'
})
class HelloWorld {
constructor() {
console.log('constructor被调用,但和Angular无关');
}
}
// 生成类实例,此时会调用constructor
new HelloWorld();
所以就出现了ngOnInit;
ngOnInit的作用根据官方的说法:
ngOnInit用于在Angular第一次显示数据绑定和设置指令/组件的输入属性之后,初始化指令/组件
所以总的来说:
1.ngOnChanges当数据绑定输入属性的值发生变化时候调用;
2.ngOnInit( )在第一次ngOnChanges( )后调用;说明这两个方法一般是配合工作的;
3.ngOnInit()用于Angular获取输入属性后初始化组件,此方法是钩子方法,在ngOnChanges()方法被调用之后使用;
4.ngOnInit()钩子只会被调用一次;
ngOnInit属于Angular生命周期的一部分,其在第一轮ngOnChanges完成之后调用,并且只调用一次:
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
import { Component, ElementRef } from '@angular/core';
@Component({
selector: 'hello-world',
templateUrl: 'hello-world.html'
})
class HelloWorld {
constructor(private elementRef: ElementRef) {
// 在类中就可以使用this.elementRef了
}
}
在constructor中注入的依赖,就可以作为类的属性被使用了。
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); // 传入的数据
}
}
所以,我们可以在ngOnInit中做一些初始化的操作,可以在组件的ngOnInit中操作父组件传递到子组件的一些shu数据;
所以,开发中我们经常在ngOnInit做一些初始化的工作,而这些工作尽量要避免在constructor中进行,constructor中应该只进行依赖注入而不是进行真正的业务操作。
ngOnInit方法只是初始化angular的组件和指令,并不是真正的dom加载完成
html代码:
typescript代码:
这个时候oBox1无法获取到DOM节点,这是因为ngOnInit方法只是初始化angular的组件和指令,并不是真正的dom加载完成。
如果要获取到oBox1,可以在ngAfterViewInit方法里获取,该方法是指页面渲染完成之后触发!
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
--结束END--
本文标题: Angular2中constructor和ngOninit的使用讲解
本文链接: https://www.lsjlt.com/news/147901.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-01-12
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0