检测@Input 属性 angular 4 的内部变化
Detect internal change to @Input property angular 4
我知道当来自其父组件的组件 @Input 属性 时会触发 ngOnChanges。但是我如何检测 @Input 属性 是否在其组件内发生了变化。我一直没能找到一个好的答案。
谢谢
为此,您可以使用 ngOnChanges()
生命周期方法,如较早的答案中所述:
@Input() yourInput: string;
ngOnChanges(changes: SimpleChanges) {
this.doSomething(changes.yourInput.currentValue);
// You can also use yourInput.previousValue and
}
您可以使用需要被父组件捕获的 Output() 或事件发射器。
您可以在 setter 方法上定义 @Input()
,这样您就可以在为属性设置新值时执行其他操作。
下面是一个示例组件,演示了这一点:
import { Component, Input } from '@angular/core';
@Component({
selector: 'hello',
template: `<h1 (click)="name = 'Bye'">{{name}}!</h1>`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
private _name: string;
get name() {
console.log("Returning name", this._name);
return this._name;
}
@Input()
set name(newName) {
console.log("Setting new name", newName);
this._name = newName;
}
}
这个组件在另一个组件中使用时,可以像下面这样指定:
<hello [name]="'Hi'"></hello>
在 aboe 示例中,Hi
的初始值是从 external/parent 组件设置的,单击文本时,值会更新为组件内部的 Bye
。在这两种情况下,您都会在浏览器控制台中观察到 console.log
语句。
我知道当来自其父组件的组件 @Input 属性 时会触发 ngOnChanges。但是我如何检测 @Input 属性 是否在其组件内发生了变化。我一直没能找到一个好的答案。 谢谢
为此,您可以使用 ngOnChanges()
生命周期方法,如较早的答案中所述:
@Input() yourInput: string;
ngOnChanges(changes: SimpleChanges) {
this.doSomething(changes.yourInput.currentValue);
// You can also use yourInput.previousValue and
}
您可以使用需要被父组件捕获的 Output() 或事件发射器。
您可以在 setter 方法上定义 @Input()
,这样您就可以在为属性设置新值时执行其他操作。
下面是一个示例组件,演示了这一点:
import { Component, Input } from '@angular/core';
@Component({
selector: 'hello',
template: `<h1 (click)="name = 'Bye'">{{name}}!</h1>`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
private _name: string;
get name() {
console.log("Returning name", this._name);
return this._name;
}
@Input()
set name(newName) {
console.log("Setting new name", newName);
this._name = newName;
}
}
这个组件在另一个组件中使用时,可以像下面这样指定:
<hello [name]="'Hi'"></hello>
在 aboe 示例中,Hi
的初始值是从 external/parent 组件设置的,单击文本时,值会更新为组件内部的 Bye
。在这两种情况下,您都会在浏览器控制台中观察到 console.log
语句。