问题描述
有2个组件:parentComponent和ChildComponent,它们在父级内部定义.在parentComponent中,有一个局部变量,该变量用作值传递给ChildComponent的输入属性(使用吸气剂).
There are 2 components: parentComponent and ChildComponent, which is defined inside the parent.In the parentComponent there is a local variable which is used as value to pass to an input property of the ChildComponent (using a getter).
ParentComponent.ts:
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:
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),该函数代码如下:
The issue is: in some place in the parent component, when specific event occurs, a function newPersonArrived(newPerson:PersonData) is being called, the function code is as following:
newPersonArrived(newPerson:Person){
this.PersonData = newPerson;
}
这不会以新的人名影响用户界面!
This doesn't affect the UI with the new person name!
只有以下帮助:
newPersonArrived(newPerson:Person){
this.PersonData = new Person();
this.PersonData.firstName = newPerson.firstName;
}
这是预期的行为吗?
为什么只有当personData初始化为新的Person时,UI才能捕获"更改?
why only when the personData is initialized to new Person, the UI "catches" the change?
推荐答案
请注意您对子组件的更改
please watch for your changes in child component
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...
}
这篇关于Angular 4 @Input属性更新不会影响UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!