[英]angular2 input value bind from another input with ngmodel directive
[英]angular2 ngModel with value from @Input
我正在嘗試在我的子組件中使用[(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, 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只能單向工作。 當父級更改Input的值時,子級會收到通知。 但是,如果您只使用@Input,則父級不會意識到對子級的任何更改。
繼續@GünterZö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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.