Ayy*_*ash 7 angular-components angular
在这里参考Angular2文档文件:[ https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#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; }
}
Run Code Online (Sandbox Code Playgroud)
父母很简单:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
您希望控制台在3秒内三次注销"名称更改".它没有,它记录一次,并忽略后续集(只有在值没有改变时才会发生这种情况).无论值是否发生变化,如何使输入选择设置事件?
我看到两种解决方法:
1)使用不可变值
setTimeout(() => {
this.name = new String("a");
setTimeout(() => {
this.name = new String("a");
setTimeout(() => {
this.name = new String("a");
}, 1000);
}, 1000);
}, 1000);
Run Code Online (Sandbox Code Playgroud)
2)直接更改输入属性
@ViewChild(NameChildComponent) child: NameChildComponent;
setTimeout(() => {
this.child.name = "a";
setTimeout(() => {
this.child.name = "a";
setTimeout(() => {
this.child.name = "a";
}, 1000);
}, 1000);
}, 1000);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3736 次 |
| 最近记录: |