如何将json 'oup' 值从子组件更新为父组件 . 当我尝试将输出事件的子模型中的值更新为父组件时,无效 .
我在下面提供了所有细节
数据处理:
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);
}
}
2 回答
这看起来有点奇怪 . 您将
fello
值分配给输入,然后发出更新的值 . 在我看来,你想要发出改变后的sharedVar
您是否有理由将数组作为输入而不仅仅是字符串发送? plnkr
看your sample有一些奇怪的事情:
sharedVar
数组作为输入,并在更新子文本框值时从 Launcher 输出字符串 . 当发生这种情况时,父对象中的绑定会将sharedVarParent
更改为字符串,从而弄乱整个事情 . 当父实例化子项时,它将输入sharedVar
设置为数组 . 当您输入子项的文本框时,它会输出一个字符串,父项将sharedVarParent
更改为字符串,然后将其作为输入发送给子项 . plnkr