Angular:从子组件向表单添加控件

3
在Angular 2中,我有一个包含输入的子组件。我想将此输入(控件)添加到父组件表单(NgForm)中。
目前,为了简单起见,我正在使用模板驱动表单。
我看到了这个答案,但认为它可能已过时:在Angular 2中将控件添加到父组件的表单 子组件模板: formInputName是一个输入绑定,以便我可以重用此组件并动态添加'name'属性。
<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 完成它。不确定需要在模板中添加什么,或者如何在控制器中以编程方式完成。

Plunker: https://plnkr.co/edit/rDluyJduyHF7vclK9wRE?p=preview


你能创建一个 Plunker 吗? - Max Koretskyi
https://plnkr.co/edit/rDluyJduyHF7vclK9wRE?p=preview - mrshickadance
你需要为 test-component 组件实现 ControlValueAccessor。请参阅在 Angular 表单中实现 ControlValueAccessor 时再也不会感到困惑。阅读文章后,您可以编辑您的问题以添加一些澄清。 - Max Koretskyi
1个回答

8

你能否尝试这个方法,并看看是否有效?

子组件

@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
}

子模板

<input #myControl="ngModel" class="text-input" [name]="formInputName" [id]="formInputName" type="text" [(ngModel)]="searchValue"
            (change)="onChange(searchValue)"
            (blur)="onBlur()"
            (focus)="onFocus()"
            [required]="isRequired">

父模板

<child-component (childControl)="childControlReady($event)"></child-component>

父组件

childControlReady(control: NgModel) {
 this.testform.addControl(control);
}

1
太棒了,谢谢!#myControl 给我提供了 ngModel 的引用是关键。 - mrshickadance
当使用ReactiveForms(我没有使用ngModel)时,EventEmitter应该返回什么?我尝试了这个解决方案,但是新添加的控件在添加到表单组后不会更新其值。 - gerb0n

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接