【发布时间】:2016-12-10 03:13:22
【问题描述】:
如何将 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(); }
}
子组件
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);
}
}
【问题讨论】:
-
当它实际上是
Array<any>或具有“inp”和“oup”属性的任何类型的数组时,您将其声明为字符串。我不认为这是问题所在。似乎您正在将输入的模型设置为数组中第一个元素(字符串)的“oup”属性并在更改中发出它。这不会用输入到输入中的字符串值覆盖sharedVarParent(对象数组)吗? -
@JasonGoemaat 即使更改了数据类型 @Input() sharedVar: Array
问题仍然存在,请问还有其他建议吗?谢谢。 -
Angular 似乎不会将 nutbox 输入 for primitives 确认为与父级关联。
<input name="parent-notes" [(ngModel)]="parent.notes" />将起作用,因为原始值 (notes: string) 是在对象的命名空间之外声明的;但<input name="child-notes" [(ngModel)]="notes" />似乎失去了对父母和祖父母的提及。这与 Angular1.x 中的情况没有什么不同,因为您必须使用愚蠢的对象来保持数据绑定活动。但是他们怎么可能在 ng2 中忽略了这一点???我猜你必须使用ControlValueAccessor。
标签: json typescript angular parent-child