Angular 4 @Input属性更新不会影响UI

时间:2017-05-09 06:23:37

标签: javascript angular ngonchanges

有两个组件:parentComponent和ChildComponent,它们在父组件内定义。 在parentComponent中有一个局部变量,它用作值传递给ChildComponent的输入属性(使用getter)。

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;
    }

这不会影响具有新人名的UI!

只有以下方面有帮助:

newPersonArrived(newPerson:Person){
    this.PersonData = new Person();
    this.PersonData.firstName = newPerson.firstName;
    }

这是预期的行为吗?

为什么只有当personData被初始化为新的Person时,UI才会捕获&#34;改变?

1 个答案:

答案 0 :(得分:3)

请注意您对子组件的更改

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

 }