在 Angular 2 中,我有一个包含输入的子组件。我想将此输入(控件)添加到父组件表单(NgForm)。
为了简单起见,我目前正在使用模板驱动表单。
我看到了这个答案,但认为它可能已经过时了?:Angular 2 Add control to parent component's form
子组件模板: formInputName 是一个输入绑定(bind),因此我可以重用该组件,并动态添加“名称”属性。
<input class="text-input" [name]="formInputName" [id]="formInputName" type="text" [(ngModel)]="searchValue"
(change)="onChange(searchValue)"
(blur)="onBlur()"
(focus)="onFocus()"
[required]="isRequired">
在父组件上,我有一个表单实例:
@ViewChild('testForm') testForm: NgForm;
如何将子组件控件添加到 NgForm 的这个实例中?我不确定如何使用 addControl .不确定我需要在模板中添加什么,或者如何在 Controller 中以编程方式添加。
Plunker:https://plnkr.co/edit/rDluyJduyHF7vclK9wRE?p=preview
最佳答案
你可以试试这个,看看它是否有效,
Child component
@Output() childControl = new EventEmitter<NgModel>(); // import { NgModel } from '@angular/forms';
@ViewChild('myControl') myControl: NgModel;
ngAfterViewInit() {
this.childControl.emit(myControl); // emitting the control to the parent to be picked up there and added to the main form
}
Child template
<input #myControl="ngModel" class="text-input" [name]="formInputName" [id]="formInputName" type="text" [(ngModel)]="searchValue"
(change)="onChange(searchValue)"
(blur)="onBlur()"
(focus)="onFocus()"
[required]="isRequired">
Parent template
<child-component (childControl)="childControlReady($event)"></child-component>
Parent component
childControlReady(control: NgModel) {
this.testform.addControl(control);
}
关于Angular将控件添加到子组件的表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46241768/