7

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

}

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 初始化为 new Person 时,UI 才会“捕捉”变化?

4

1 回答 1

7

请注意您对子组件的更改

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

 }
于 2017-05-09T06:30:17.520 回答