从子组件到窗体的角度添加控件

mrs*_*nce 1 typescript angular

在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">
Run Code Online (Sandbox Code Playgroud)

在父组件上,我具有以下形式的实例:

    @ViewChild('testForm') testForm: NgForm;
Run Code Online (Sandbox Code Playgroud)

如何将子组件控件添加到此NgForm实例?我不确定如何用addControl做到这一点。不知道我需要在模板中添加什么,或者不确定如何在控制器中以编程方式进行添加。

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

ama*_*mal 5

您可以尝试一下,看看是否可行,

子组件

@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
}
Run Code Online (Sandbox Code Playgroud)

子模板

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

父模板

<child-component (childControl)="childControlReady($event)"></child-component>
Run Code Online (Sandbox Code Playgroud)

父组件

childControlReady(control: NgModel) {
 this.testform.addControl(control);
}
Run Code Online (Sandbox Code Playgroud)