How to update the json 'oup' value from a child component to parent component. When i try to update the value from child model with output event in to a parent component nothing works.
i given all the details below
Data Handled:
json: [{
"inp": "hello",
"oup": "fello"
}]
parent component
// 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);
}
}
This looks a bit weird to me. You assign the fello
value to the input and then emit the updated value. It seems to me you want to emit the changed sharedVar
instead
<input [(ngModel)]="sharedVar[0].oup" (ngModelChange)="change()">
change() {
this.sharedVarChange.emit(sharedVar);
}
Is there a reason you send your array as the input instead of just the string? plnkr
Looking at your sample there are a few odd things:
Your parent input is a one way binding, I don't know if that is confusing you, it's unusual and adds confusion to the question (fixed)
<input [(ngModel)]="sharedVarParent[0].oup"/>
Since the array is passed by reference as input, there's not really a need for an output of your child component unless you are creating a new array, just use two-way binding on the input in your child and it will update the property on the first object in the shared array (sample)
<input [(ngModel)]="sharedVar[0].oup">
sharedVar
array as input and outputting a string from the emitter when the child's text box value is updated. When that happens, the binding in the parent changes sharedVarParent
to be a string, messing the whole thing up. When the parent instantiates the child, it sets the input sharedVar
to the array. When you type in the child's textbox it outputs a string and the parent changes sharedVarParent
to be a string, which is then sent as input to the child. plnkr
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.