具有来自@Input 的值的angular2 ngModel

angular2 ngModel with value from @Input

我正在尝试在我的 child-component 中使用 [(ngModel)],并通过 @Input() 从我的 parent 传递到我的 child 组件中的字符串。

但是 two-way-binding 似乎不起作用。字符串从 parent 正确传入,但是当我在 child 中编辑它时,parent 的值没有得到更新。

我错过了什么?

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

  }
}

我创建了一个 plnkr 来说明这个问题:https://plnkr.co/edit/jCF5kt73P38EFYUAZF6l

您需要一个输出来通知更改:

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

  }
}

是的 - @Input 只能以一种方式工作。当 parent 更改 Input 的值时,child 会收到通知。但是 parent 不知道 child 的任何更改,如果您 使用 @Input.

为了继续@Günter Zöchbauer 的回答,我也修改了 app.ts 文件。

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);
  }
}