我试图在我的子组件中使用(ngModel),通过@ via ()将一个字符串从我的父组件传递到我的子组件。
然而,双向绑定似乎不起作用。正确地从父字符串传入字符串,但当我在子字符串中编辑它时,父字符串的值不会被更新。
我遗漏了什么?
父级:
@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
发布于 2017-04-21 12:26:13
您需要一个输出来通知更改:
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() {
}
}发布于 2017-04-21 12:46:09
是的-@输入只有一种方式。当父级更改输入的值时,会通知子节点。但是,如果您只使用@Input,则父程序不知道子程序是否有任何更改。
发布于 2017-04-21 12:48:37
为了继续@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 {}孩子
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);
}
}https://stackoverflow.com/questions/43542645
复制相似问题