如何更新從子組件到父組件的值的「子」值。 當我嘗試更新從輸出事件中的子模型到父組件的值無效。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);
}
}
你正在聲明它作爲一個字符串時確實是'陣列'或任何類型的陣列具有「INP」和「OUP」屬性。我不認爲這是問題。好像你正在將輸入的模型設置爲數組中第一個元素的'oup'屬性(一個字符串)並在變化中發送它。這不會用輸入到輸入中的字符串值覆蓋'sharedVarParent'(一個對象數組)嗎? –
@JasonGoemaat即使更改了數據類型@Input()sharedVar:Array問題退出,請提出任何其他建議?謝謝。 –
看起來Angular不會承認母函數輸入爲*與母函數關聯。由於原始值('notes:string')是從對象的名稱空間聲明的,所以''但是''似乎失去了對父母和祖父母的提及。這與Angular1.x不同,當你不得不使用一個愚蠢的對象來保持數據綁定的存在時。但他們怎麼可能在ng2中忽略了這個?我想你必須使用'ControlValueAccessor'。 – Cody