[英]angular2 pass ngModel to a child component
我有ParentComponent和ChildComponent,我需要將ParentComponent中的ngModel傳遞給ChildComponent。
// the below is in ParentComponent template
<child-component [(ngModel)]="valueInParentComponent"></child-component>
如何在ChildComponent中獲取ngModel的值並進行操作?
您需要在子類中實現ControlValueAccessor
。 它將您的組件定義為“具有值”,可以使用角度方式綁定。
在這里閱讀更多相關信息: http : //blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html
對於Parent - > Child,請使用@Input
對於Child - > Parent,請使用@Output
所以要同時使用:
在父組件中
打字稿:
onValueInParentComponentChanged(value: string) {
this.valueInParentComponent = value;
}
HTML
<child-component
(onValueInParentComponentChanged)="onValueInParentComponentChanged($event)"
[valueInParentComponent]="valueInParentComponent">
</child-component>
在子組件中
打字稿:
export class ChildComponent {
@Input() valueInParentComponent: string;
@Output() onValueInParentComponentChanged = new EventEmitter<boolean>();
}
onChange(){
this.onValueInParentComponentChanged.emit(this.valueInParentComponent);
}
HTML
<input type="text" [(ngModel)]="valueInParentComponent"
(ngModelChange)="onChange($event)"/>
完整的例子
https://plnkr.co/edit/mc3Jqo3SDDaTueNBSkJN?p=preview
其他實現方法:
https://angular.io/docs/ts/latest/cookbook/component-communication.html
聽起來你正在嘗試包裝表單控件。 我寫了一個圖書館來幫助你做到這一點! s-ng-utils
有一個用於父組件的超類: WrappedFormControlSuperclass
。 你可以像這樣使用它:
@Component({
template: `
<!-- anything fancy you want in your parent template -->
<child-component [formControl]="formControl"></child-component>
`,
providers: [provideValueAccessor(ParentComponent)],
})
class ParentComponent extends WrappedFormControlSuperclass<ValueType> {
// This looks unnecessary, but is required for Angular to provide `Injector`
constructor(injector: Injector) {
super(injector);
}
}
這假設<child-component>
有一個ControlValueAccessor
,正如@Amit的答案所示。 如果您自己編寫<child-component>
,那么s-ng-utils
還有一個超類來幫助它: FormControlSuperclass
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.