Angular将控件添加到子组件的表单

标签 angular typescript

在 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/

相关文章:

javascript - 在 Angular 应用程序之间共享脚本

angular - 无法更改 Angular 垫表列顺序

javascript - 如何在 TypeScript 中返回具有此自定义类型的 Promise?

visual-studio - 在 typescript 中导入模块时绝对路径的根是什么?

javascript - 在 Angular 2 中嵌入组件

javascript - 在 JavaScript/TypeScript 中将项目添加到数组末尾

angularjs - MEAN 堆栈的 .net 技术中是否有类似的技术/服务,例如控制台应用程序?

javascript - Angular 组件中注入(inject)的 stub 服务返回错误值

angular - 为什么验证器规则在我的 Angular 项目中使用这个响应式(Reactive)表单示例似乎不起作用?

mysql - ER_BAD_FIELD_ERROR : Unknown column 'table.column' in 'on clause'