2017-05-09 17 views
0

parentComponentとChildComponentの2つのコンポーネントがあります。これは親の内部で定義されています。 parentComponentには、(getterを使用して)ChildComponentの入力プロパティに渡す値として使用されるローカル変数があります。角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; 
    } 

これはありません新しい人名で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 = preview – 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)で呼び出されていません、 )、この場合はUIが更新され、ngOnChangesは必要ありません.... – Batsheva

関連する問題