【发布时间】:2017-05-02 16:08:23
【问题描述】:
在此处参考 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 秒内注销“名称更改”三次。它没有,它只记录一次,并忽略后续集合(仅当值不变时才会发生这种情况)。无论值是否改变,如何让输入拾取设置事件?
【问题讨论】:
-
您不会更改输入,而是一遍又一遍地发送相同的值。
-
我知道,那为什么“setter”不起作用?
-
我猜它会检查值是否发生了变化,因为没有,所以什么都没有发生
-
这不是它与普通 setter 和 getter 的行为方式,只有当它附加到子组件时,我希望有办法以某种方式将该行为传递给子组件,我需要捕获集合事件,即使值没有改变
-
这没有任何意义。如果输入没有改变,监听器不会触发。也许你应该传递另一个标志或其他东西作为输入。
标签: angular angular-components