javascript-Angular 4 @Input属性更新不会影响用户界面

有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...

 }

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...