具有来自@Input 的值的angular2 ngModel

标签 angular typescript angular2-forms

我正在尝试在我的子组件中使用 [(ngModel)],并通过 @Input() 从我的父组件传递到我的子组件中。

但是双向绑定(bind)似乎不起作用。该字符串正确地从父级传入,但是当我在子级中编辑它时,父级的值没有得到更新。

我错过了什么?

家长:

@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 的值的angular2 ngModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43542645/

相关文章:

Angular Material不能用主题改变背景颜色

angular - 如何使用 HttpTestingController 刷新 header ?

typescript - 使用桶导入模块与特定文件对包大小有何影响?

javascript - 编写一个易于使用的 Typescript 框架

angular - 将禁用与模型驱动形式一起使用

html - 使用 Angular2 单击更改图像

angular - 如何设置初始 Electron Angular 项目

javascript - 观察者确认是如何运作的?

javascript - 如何在 Typescript 1.8 中包含未类型化的节点模块?

javascript - Angular 2 : Unable to create custom validator class