2016-08-04 24 views
2

如何更新從子組件到父組件的值的「子」值。 當我嘗試更新從輸出事件中的子模型到父組件的值無效。Angular 2 [typescript]使用json模型從子組件UI更新父組件UI的模型值

我給出處理的下方

數據的所有細節:

json: [{ 
     "inp": "hello", 
     "oup": "fello" 
}] 

父組件

// Parent Component 
@Component({ 
selector: 'parent', 
template: ` 
    <div>Parent sharedVarParent: {{sharedVarParent[0].oup}} 
    <input type="text" [ngModel]="sharedVarParent[0].oup"/> 
    </div> 
    <child [(sharedVar)]="sharedVarParent"></child> 

     `, 
    directives: [ChildComponent] 
}) 
export class ParentComponent { 
    sharedVarParent =[{ 
        "inp": "hello", 
        "oup": "fello" 
        }] 

    constructor() { console.clear(); } 
} 

childcomponent

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

    // Child Component 
    @Component({ 
    selector: 'child', 
    template: ` 
    <p>Child sharedVar: {{sharedVar[0].oup}}</p> 
    <input [ngModel]="sharedVar[0].oup" (ngModelChange)="change($event)"> 
    ` 
    }) 
    export class ChildComponent { 
    @Input() sharedVar: string; 
    @Output() sharedVarChange = new EventEmitter(); 
    change(newValue) { 
     console.log('newvalue', newValue) 
     this.sharedVar = newValue; 
     this.sharedVarChange.emit(newValue); 
    } 
} 
+0

你正在聲明它作爲一個字符串時確實是'陣列'或任何類型的陣列具有「INP」和「OUP」屬性。我不認爲這是問題。好像你正在將輸入的模型設置爲數組中第一個元素的'oup'屬性(一個字符串)並在變化中發送它。這不會用輸入到輸入中的字符串值覆蓋'sharedVarParent'(一個對象數組)嗎? –

+0

@JasonGoemaat即使更改了數據類型@Input()sharedVar:Array 問題退出,請提出任何其他建議?謝謝。 –

+0

看起來Angular不會承認母函數輸入爲*與母函數關聯。由於原始值('notes:string')是從對象的名稱空間聲明的,所以''但是''似乎失去了對父母和祖父母的提及。這與Angular1.x不同,當你不得不使用一個愚蠢的對象來保持數據綁定的存在時。但他們怎麼可能在ng2中忽略了這個?我想你必須使用'ControlValueAccessor'。 – Cody

回答

2

這看起來有點怪我。您將fello值分配給輸入,然後發出更新的值。在我看來,要發出改變sharedVar代替

<input [(ngModel)]="sharedVar[0].oup" (ngModelChange)="change()"> 
change() { 
    this.sharedVarChange.emit(sharedVar); 
} 
+0

我試過你的解決方案,它不更新父組件的UI模型。任何建議來實現這種情況,謝謝。 –

+0

你可以提供一個Plunker重現和調查? (模板https://angular.io/resources/live-examples/quickstart/ts/plnkr.html) –

+0

你可以在http://plnkr.co/edit/PJqvLs?p=preview獲得。請檢查它,謝謝 –

1

有你把你的數組作爲輸入,而不只是字符串理由嗎? plnkr

看着your sample有一些奇怪的事情:

  1. 你父母的輸入是一個單向綁定,我不知道這是混淆了你,這是不尋常的,並增加了混亂的問題(fixed)

    <input [(ngModel)]="sharedVarParent[0].oup"/> 
    
  2. 由於陣列通過引用作爲輸入傳遞,有沒有真正需要你的子組件的輸出,除非你正在創建一個新的數組,只需使用雙向綁定在你的孩子的輸入,它會共享陣列在更新第一對象上的屬性(sample)

    <input [(ngModel)]="sharedVar[0].oup"> 
    
  3. 你混合傳遞sharedVar數組作爲輸入,並輸出一當孩子的文本框值更新時,從發射器發出的字符串。當發生這種情況時,父母中的綁定將sharedVarParent更改爲一個字符串,將整個事件搞亂。當父級實例化子級時,它將輸入sharedVar設置爲該數組。當你輸入孩子的文本框時,它會輸出一個字符串,父母將sharedVarParent更改爲一個字符串,然後將其作爲輸入發送給孩子。 plnkr