我正在尝试在我的子组件中使用[(ngModel)],其中一个字符串通过@Input()从我的父组件传递到我的子组件.
然而,双向绑定似乎不起作用.字符串正确地从父项传入,但是当我在子项中编辑它时,父项的值不会更新.
我错过了什么?
家长:
@Component({ selector: 'my-app',template: ` <div> <child [(value)]="name"></child> <p>{{name}}</p> </div> `,}) export class App { name:string = 'MyValue'; constructor() { } }
儿童
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,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() { } }