如何将表单控件添加到现有表单组中 - angular2

问题描述 投票:0回答:5

我有一个在 ngOninit 中构建的表单组,但稍后当单击其中一个控件时,我想根据从 ngOninit 中的另一个 API 获取的值向该现有表单组添加更多控件。下图为实际需求。当我单击其他角色时,我想显示从 API 获得的其他角色控件。enter image description here

由于我是 angular2 的新手,任何人都可以帮助我摆脱这个问题吗?

angular angular2-template angular2-forms angular2-services
5个回答
2
投票

您可以尝试以下方法。

 const arrayControl = <FormArray>this.myForm.controls['formArray'];
        let newGroup = this.fb.group({
            /// new controls
        }
        arrayControl.push(newGroup);

0
投票

如果您有要求,您可以添加一个方法来控制并在表单上进行验证。

类似:

<button type="submit" (click)="save(f.value, f.valid)">Submit</button>

在您的

save()
方法中,您可以验证表单等。

有关 Angular 2 中表单控件的更多信息:https://scotch.io/tutorials/how-to-deal-with- Different-form-controls-in-angular-2

更新:

由于您是 Angular 2 的新手,因此这对您来说是“必读”内容: https://angular.io/docs/ts/latest/cookbook/dynamic-form.html 了解动态表单在 Angular2 中的行为方式以及如何实现它们非常有用。

更新2:

我不太明白你的问题。如果您想要动态添加元素到表单中,最简单的方法是使用

*ngIf

来动态显示/隐藏元素。

示例:

<input type="text" *ngIf="showInput"/>

文档:
NgIf 指令


0
投票
addControl

在角度文档中查看更多内容:

https://angular.io/api/forms/FormGroup#addcontrol


0
投票

// After Initializing the FormGroup this.FormGroup.addControl( 'firstname', new FormControl('DefaultName', [Validators.required]) );

在 HTML 模板中(即 component.html)

<!-- Inside existing Form -->> <input type="text" formControlName="firstname" />



0
投票

    将导入添加到您的组件/服务中
  1. import {FormControl} from "@angular/forms";

  2. 创建新的表单控件
  3. const customControl = new FormControl( defaultValue, [Validators.required] );

  4. 在表单组中添加新定义的表单控件
  5. this.yourFormGroup.addControl('newControlName', customControl );

    
        
© www.soinside.com 2019 - 2025. All rights reserved.