Angular2 ngModel with value from @Input

I am trying to use [(ngModel)] in my child component with a string passed from my parent to my child component via @Input ().

However, two-way binding does not work. The string is passed from the parent correctly, but when I edit it in the child, the parent value is not 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 plnkr that illustrates the problem: https://plnkr.co/edit/jCF5kt73P38EFYUAZF6l

+5
source share
3 answers

You need to display a notification of 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() { } } 
+6
source

Yes - @ Input only works in one direction. When the parent changes the value of the input, the child is notified. However, the parent is not aware of any changes for the child if you only use @Input.

0
source

Following up on @ Günter Zöchbauer’s answer, I also modified the app.ts file.

app.ts:

 //our root app component import {Component, NgModule, VERSION} from '@angular/core' import {BrowserModule} from '@angular/platform-browser' import {Child} from './child' import {FormsModule} from "@angular/forms"; @Component({ selector: 'my-app', template: ` <div> <child [value]="name" (valueChange)= "updateValue($event)"></child> <p>{{name}}</p> </div> `, }) export class App { name:string = 'MyValue'; constructor() { } updateValue(value){ this.name = value; } } @NgModule({ imports: [ BrowserModule, FormsModule ], declarations: [ App, Child ], bootstrap: [ App ] }) export class AppModule {} 

Child

 import {Component, Input, Output, EventEmitter} 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>(); constructor() { } update(value) { this.valueChange.emit(value); } } 
0
source

Source: https://habr.com/ru/post/1267019/


All Articles