有两个组件:parentComponent和ChildComponent,它在父级中定义。 在parentComponent中有一个局部变量,它用作传递给ChildComponent的输入属性的值(使用getter)。Angular 4 @Input属性更新不会影响UI
ParentComponent.ts:
@Component({
selector:'parent-component',
template:`
<h1>parent component</h1>
<child-component [personData]="PersonData"></child-component>
`
})
export class ParentComponent{
personData:Person;
get PersonData():Person{
return this.personData;
}
set PersonData(person:Person){
this.personData = person;
}
ngOnInit(){
this.PersonData = new Person();
this.PersonData.firstName = "David";
}
//more code here...
}
ChildComponent.ts:
@Component({
selector:'child-component',
template:`
<h1>child component</h1>
<div *ngIf="personData">{{personData.firstName}}</div>
`
})
export class ChildComponent{
@Input() personData:Person;
//more code here...
}
的问题是:在父组件的一些地方中,当特定事件发生时,函数newPersonArrived(newPerson:PersonData )被调用,功能代码如下:
newPersonArrived(newPerson:Person){
this.PersonData = newPerson;
}
This does not aff用新的人物名称来使用UI!
只有以下帮助:
newPersonArrived(newPerson:Person){
this.PersonData = new Person();
this.PersonData.firstName = newPerson.firstName;
}
这是预期的行为?
为什么只有当personData初始化为新的Person时,UI才会“捕捉”这个变化?
你在哪里调用'newPersonArrived'?它应该工作 – yurzui
在父组件发生某些事件后,我看到functin正在被调用(我在那里放了console.log('aa')并看到它被打印) – Batsheva
https://plnkr.co/edit/ 0SVsezfJYtc0xzKGkAZe?p =预览 – yurzui