首页 文章

Angular Add Control从子组件形成

提问于
浏览
0

在Angular 2中,我有一个包含输入的子组件 . 我想将此输入(控件)添加到父组件表单(NgForm) .

我目前正在使用模板驱动表单来简化 .

我看到了这个答案,但认为它可能已经过时了?:Angular 2 Add control to parent component's form

子组件模板: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

1 回答

  • 4

    你可以尝试一下,看看它是否有效,

    儿童组件

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

相关问题