【发布时间】:2017-10-07 08:01:05
【问题描述】:
有 2 个组件:parentComponent 和 ChildComponent,它们在 parent 内部定义。 在 parentComponent 中有一个局部变量,用作传递给 ChildComponent 的输入属性的值(使用 getter)。
父组件.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...
}
子组件.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;
}
这不会影响带有新人名的 UI!
只有以下有帮助:
newPersonArrived(newPerson:Person){
this.PersonData = new Person();
this.PersonData.firstName = newPerson.firstName;
}
这是预期的行为吗?
为什么只有当 personData 初始化为 new Person 时,UI 才会“捕捉”变化?
【问题讨论】:
-
你在哪里打电话给
newPersonArrived?它应该工作 -
在父组件中发生一些事件后,我看到函数被调用(我放在那里 console.log('aa') 并看到它被打印出来了)
-
我看到了这个例子,所以你的意思是这取决于我要参加哪个活动?听起来很有趣
-
我不太清楚。为了更好地理解它,我们需要一些工作示例
标签: javascript angular ngonchanges