2016-07-15 59 views
0

我創建了一個plunker這裏:角2雙向組件綁定不調用父ngOnChange

http://plnkr.co/edit/8bwqkYQ6tqrpGwHT588y?p=preview

,顯示問題。

基本上,我有2個組件。第一個組件具有屬性與子組件的雙向綁定。

我的父組件是:

import { Component, Input, Output, EventEmitter } from '@angular/core' 
import { ChildComponent } from "./childComponent" 

@Component({ 
    selector: 'parentComponent', 
    template: ` 
    <div> 
     <a href="#" (click)="selectedId = 0">Reset</a><br> 
     <div>Parent SelectedId: {{selectedId}}</div> 
     <childComponent [(selectedId)]="selectedId"></childComponent> 
    </div> 
    `, 
    directives: [ChildComponent] 
}) 

export class ParentComponent { 
    @Input() selectedId: number; 

    ngOnChanges(changes) { 
     console.log("Parent changes called!"); 
    } 
} 

和我的孩子組成:

import { Component, Input, Output, EventEmitter } from '@angular/core' 

@Component({ 
    selector: 'childComponent', 
    template: ` 
    <div> 
     <div>Child SelectedId: {{selectedId}}</div> 
    </div> 
    `, 
    directives: [] 
}) 

export class ChildComponent { 
    @Input() selectedId: number; 
    @Output() selectedIdChange: EventEmitter<number> = new EventEmitter<number>(); 

    constructor() { 
     setTimeout(() => { 
     this.selectedId = 100; 
     this.selectedIdChange.emit(this.selectedId); 
     }, 2000); 
    } 

    ngOnChanges(changes) { 
     console.log("Child changes called!"); 
    } 
} 

在孩子,我設置了超時2秒後編程改變selectedId的值,然後發出價值回到父母。

這一切的偉大工程,除了一件事......父的ngOnChange纔會被調用一次。

我會認爲父母非常想知道孩子是否已經改變了值,否則2路綁定的意義何在?

我在這裏錯過了什麼?

回答

1

只有當應用程序的selectedId發生更改時,纔會調用父項的ngOnChange,因爲這是ParentComponent的輸入屬性綁定的內容。

如果您希望父被通知在孩子所做的更改,綁定到xChange事件(其中x是輸入屬性的名稱)–即分手的財產和事件綁定:

<childComponent [selectedId]="selectedId" (selectedIdChange)="changed($event)"></childComponent> 
changed(newValue) { 
    console.log('newValue', newValue); 
    this.selectedId = newValue; 
} 

Plunker

+1

可我只是說這是真的,真的很愚蠢。什麼時候你不想讓你的父組件被通知,當你明確地將它設置爲雙向綁定時,屬性發生了變化?它應該自動將變化事件向上冒泡。 – Scottie

+0

@Scottie,好了,有時你只是想父(例如,父視圖)進行更新,並且不需要通知,因爲你並不需要當孩子做了更改執行任何邏輯。而且你是正確的,EventEmitter發出的事件不會冒泡。如果您希望通知多個組件發生單個更改,則推薦使用共享服務中的Observable或Subject。 –