在这里参考Angular2文档文件:[https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child-setter](Parent to child setter),我有以下子组件代码:
import { Component, Input } from '@angular/core';
@Component({
selector: 'name-child',
template: '<h3>"{{name}}"</h3>'
})
export class NameChildComponent {
private _name = '';
@Input()
set name(name: string) {
console.log("name change");
this._name = name;
}
get name(): string { return this._name; }
}
父母很简单:
import { Component } from '@angular/core';
@Component({
selector: 'name-parent',
template: `
<h2>Parent </h2>
<name-child [name]="name"></name-child>
`
})
export class NameParentComponent {
// somewhere on ngOnInit, set name without changing value
ngOnInit() {
// get pending paged only and so on
setTimeout(() => {
this.name = "a";
setTimeout(() => {
this.name = "a";
setTimeout(() => {
this.name = "a";
},1000);
},1000);
},1000);
}
}
您希望控制台在3秒内三次注销“名称更改” . 它没有,它记录一次,并忽略后续集(只有在值没有改变时才会发生这种情况) . 无论值是否发生变化,如何使输入选择设置事件?
3 回答
我看到两种解决方法:
1)使用不可变值
2)直接更改输入属性
你明确提到的文章说
当你想要实现的目标不是跟踪变化时 . 这是关于从父母到孩子发送一个事件,这是RX
Subject
(其中4个中的任何一个)或Angular2EventEmitter
非常好的地方 .您可以在父级中创建其中一个并将其传递给子级 . 然后,在您订阅它之后,您可以跟踪所有事件而不管其值如何 .
如果使用输入设置器是一个严格的要求,但是你尝试过使用OnChanges,这不是正面的吗?