I'm trying to use [(ngModel)] within my child-component with a string passed from my parent into my child component via @Input().
However the two-way-binding does not seem to work. The string gets passed in from the parent correctly, but when I edit it in the child the parent's value does not get updated.
What am I missing?
Parent:
@Component({
selector: 'my-app',
template: `
<div>
<child [(value)]="name"></child>
<p>{{name}}</p>
</div>
`,
})
export class App {
name:string = 'MyValue';
constructor() {
}
}
Child
import {Component, Input} from '@angular/core'
@Component({
selector: 'child',
template: `
<div>
<p>My custom input</p>
<textarea [(ngModel)]="value"></textarea>
</div>
`,
})
export class Child {
@Input() value:string;
constructor() {
}
}
I created a plnkr which illustrates the issue: https://plnkr.co/edit/jCF5kt73P38EFYUAZF6l
You need an output to notify about changes:
import {Component, Input} from '@angular/core'
@Component({
selector: 'child',
template: `
<div>
<p>My custom input</p>
<textarea [(ngModel)]="value" (ngModelChange)="update($event)"></textarea>
</div>
`,
})
export class Child {
@Input() value:string;
@Output() valueChange:EventEmitter<string> = new EventEmitter<String>()
update(value) {
this.valueChange.emit(value);
}
constructor() {
}
}
Yeah - @Input only works one way. When the parent changes the value of Input the child gets notified. However the parent is unaware of any changes to the child, if you are only using @Input.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With