有2个组件:parentComponent和ChildComponent,它们在父级内部定义.
在parentComponent中,有一个局部变量,用作值传递给ChildComponent的输入属性(使用吸气剂).
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;
}
这不会以新的人名影响用户界面!
仅以下内容有帮助:
newPersonArrived(newPerson:Person){
this.PersonData = new Person();
this.PersonData.firstName = newPerson.firstName;
}
这是预期的行为吗?
为什么只有当personData初始化为新的Person时,UI才能“捕获”更改?
解决方法:
请注意您对子组件的更改
import { Component, Input, Output, OnChanges, EventEmitter, SimpleChanges } from '@angular/core';
@Component({
selector:'child-component',
template:`
<h1>child component</h1>
<div *ngIf="personData">{{personData.firstName}}</div>
`
})
export class ChildComponent implements OnChanges{
@input() personData:Person;
public ngOnChanges(changes: SimpleChanges) {
if ('personData' in changes) {
//some code here
}
}
//more code here...
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。