Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular2 ngModel with value from @Input

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

like image 618
Korgen Avatar asked Apr 21 '17 12:04

Korgen


2 Answers

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() {

  }
}
like image 101
Günter Zöchbauer Avatar answered Sep 27 '22 20:09

Günter Zöchbauer


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.

like image 34
Aardvark Avatar answered Sep 27 '22 21:09

Aardvark