我正在尝试在我的子组件中使用 [(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/