2017-05-09 75 views
0

有两个组件:parentComponent和ChildComponent,它在父级中定义。 在parentComponent中有一个局部变量,它用作传递给ChildComponent的输入属性的值(使用getter)。Angular 4 @Input属性更新不会影响UI

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

This does not aff用新的人物名称来使用UI!

只有以下帮助:

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

这是预期的行为?

为什么只有当personData初始化为新的Person时,UI才会“捕捉”这个变化?

+0

你在哪里调用'newPersonArrived'?它应该工作 – yurzui

+0

在父组件发生某些事件后,我看到functin正在被调用(我在那里放了console.log('aa')并看到它被打印) – Batsheva

+0

https://plnkr.co/edit/ 0SVsezfJYtc0xzKGkAZe?p =预览 – yurzui

回答

1

请留意在子组件更改

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

} 
+0

我试过这个,但是ngOnChanges没有以我尝试的第一种方式调用(this.PersonData = newPerson),只有当我做新的Person( ),但在这种情况下,用户界面已更新,我不需要ngOnChanges .... – Batsheva

相关问题