本文介绍了如何在Angular中单击按钮时将FormControl动态添加到FormArray?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 formarray 中动态添加 formcontrol(option)?我想动态地向 formarray 添加问题.单击按钮后,它应该更新显示.我正在使用角度7.

组件代码

  ngOnInit(){this.quizForm = this.fb.group({问题:this.fb.array([]),问题2:this.fb.array([]),});}//创建formcontrolcreateItem():FormGroup {返回this.fb.group({问题:,});}//推送代码genField(){this.message = true;this.questions = this.quizForm.get('questions')as FormArray;this.questions.push(this.createItem());} 

HTML模板

我想在单击按钮时动态添加表单控件选项,并且表单控件应位于 formArrayName ="questions" 内.

 < form [formGroup] ="quizForm"class ="adjust-form"< div formArrayName ="问题"* ngFor =" quizForm.get('questions').controls;的项目;令i =索引;>< div class ="col-md-10 col-sm-6 mt-3 mb-3"[formGroupName] ="i"< label> {{i +1}}-{{question}}</label>< i class ="flaticon-delete"(click)="quotquizForm.get('questions').controls.splice(i,1)'style ="font-size:9px; padding-left:80px;"></i>< div class ="row"><输入类型=文本";class ="form-control col-10".[(ngModel)] ="item.ques";formControlName =" ques"placeholder =输入您的问题"必需>< button * ngIf ="i == 0&";(click)="genField()";type ="button"class ="btn btn-次要btn-高位btn-circle btn-icon ml-4".< i class ="flaticon2-plus"</i></button></div>< div * ngIf =" item.touched&&item.invalid"class ="kt-font-danger text-left"< p>必需</p></div></div></div></form> 
解决方案

此示例将电子邮件字段动态添加到反应形式.这将使用户能够添加多个电子邮件地址(例如,住所和公司).

该演示具有以下依赖性:Angular 8,

步骤1:定义表单模型

 构造函数(私有formBuilder:FormBuilder){}ngOnInit(){this.emailForm = this.formBuilder.group({电子邮件:this.formBuilder.array([this.createEmailFormGroup()])});} 

步骤2:定义一种动态构造新的 FormGroup

的方法

  private createEmailFormGroup():FormGroup {返回新的FormGroup({'emailAddress':新的FormControl('',Validators.email),'emailLabel':新的FormControl('')})} 

步骤3:定义一种将新的 FormGroup 动态添加到 FormArray

的方法

  public addEmailFormGroup(){const emails = this.emailForm.get('emails')as FormArrayemails.push(this.createEmailFormGroup())} 

步骤4(可选):定义删除 FormGroup

的方法

  public removeOrClearEmail(i:number){const emails = this.emailForm.get('emails')as FormArray如果(emails.length> 1){emails.removeAt(i)} 别的 {emails.reset()}} 

第5步:创建HTML表单模板

 < form [formGroup] ="emailForm">< div formArrayName =电子邮件">< div class ="row";* ngFor ="让emailForm.get('emails').controls的电子邮件;让我=索引[formGroupName] ="i" 

请注意,在 formArrayName 元素内,动态电子邮件 FormGroups 是根据数组索引命名的.

最终形式

 < mat-toolbar color ="primary">Angular Form Demo-动态添加表单控件</mat-toolbar>< form class ="basic-container"[formGroup] ="emailForm"< div formArrayName =电子邮件">< div class ="row";* ngFor ="让emailForm.get('emails').controls的电子邮件;让我=索引[formGroupName] ="i"< div class ="col-1">< mat-icon class ="mt-3">电子邮件</mat-icon></div>< mat-form-field class ="col-4">< input matInput formControlName =" emailAddress"占位符=电子邮件"autocomplete =电子邮件">< mat-error * ngFor ="验证validationMsgs.emailAddress"< div * ngIf =" email.get('emailAddress').hasError(validation.type)">{{validation.message}}</div></mat-error></mat-form-field>< mat-form-field class ="col-4">< mat-label>标签</mat-label>< mat-select formControlName =" emailLabel">< mat-option * ngFor =电子邮件标签的标签"[value] ="label">.{{标签}}</mat-option></mat-select></mat-form-field>< div class ="col-3">< button class ="float-left"mat-icon-button color =主要"按钮aria-label =移除/清除";(click)="removeOrClearEmail(i)";matTooltip =删除"< mat-icon> highlight_off</mat-icon></button>< button class ="float-left"mat-icon-button color =主要"按钮aria-label =添加"(click)="addEmailFormGroup()";matTooltip ="添加>< mat-icon> add_circle_outline</mat-icon></button></div></div></div></form> 

最终组件

 从'@ angular/core'导入{Component};从'@ angular/forms'导入{FormBuilder,FormArray,FormControl,FormGroup,Validators};@零件({选择器:"form-app",templateUrl:"app.component.html"})导出类AppComponent {公共emailForm:FormGroup;公共emailLabels = ['首页','工作','其他'];公开验证邮件='emailAddress':[{类型:'email',消息:'输入有效的电子邮件'}]}构造函数(私有formBuilder:FormBuilder){}ngOnInit(){this.emailForm = this.formBuilder.group({电子邮件:this.formBuilder.array([this.createEmailFormGroup()])});}公共addEmailFormGroup(){const emails = this.emailForm.get('emails')as FormArrayemails.push(this.createEmailFormGroup())}公共removeOrClearEmail(i:number){const emails = this.emailForm.get('emails')as FormArray如果(emails.length> 1){emails.removeAt(i)} 别的 {emails.reset()}}私人createEmailFormGroup():FormGroup {返回新的FormGroup({'emailAddress':新的FormControl('',Validators.email),'emailLabel':新的FormControl('')})}} 

How can I add a formcontrol(option) dynamically in formarray? I want to dynamically add questions to a formarray. Upon clicking a button, it should update the display. I'm using angular 7.

Component code

ngOnInit() {
  this.quizForm = this.fb.group({
    questions: this.fb.array([]),
    questions2: this.fb.array([]),
  });
}
    
//creating formcontrol
createItem(): FormGroup {
  return this.fb.group({
    ques: '',
  });
}
    
//pushing code
genField() {
  this.message = true;
  this.questions = this.quizForm.get('questions') as FormArray;
  this.questions.push(this.createItem());
}

HTML Template

I want to add form control option dynamically on button click and form control should be inside the formArrayName="questions".

<form [formGroup]="quizForm" class="adjust-form">
  <div formArrayName="questions" 
    *ngFor="let item of quizForm.get('questions').controls; let i = index;">
    <div class="col-md-10 col-sm-6 mt-3 mb-3" [formGroupName]="i">
      <label>{{i +1}} - {{question}} </label>
      <i class="flaticon-delete"    
          (click)="quizForm.get('questions').controls.splice(i,1) "
          style="font-size: 9px;padding-left: 80px;">
      </i>
      <div class="row">
        <input type="text" class="form-control col-10"
            [(ngModel)]="item.ques" formControlName="ques"
            placeholder="Enter your question" required>
        <button *ngIf="i == 0" (click)="genField()" type="button"
            class="btn btn-secondary btn-elevate btn-circle btn-icon ml-4">
            <i class="flaticon2-plus"></i>
        </button>
      </div>
      <div *ngIf="item.touched && item.invalid" class="kt-font-danger text-left">
        <p>required</p>
      </div>
    </div>
  </div>
</form>
解决方案

This example dynamically adds email fields to a reactive form. This would be used to enable users to add multiple email addresses (e.g. Home and Work).

This demo has the following dependencies: Angular 8, Angular Material, Bootstrap 4

End Result (Stackblitz Demo)

Step 1: Define the form model

constructor(private formBuilder: FormBuilder) { }

ngOnInit() {
  this.emailForm = this.formBuilder.group({
    emails: this.formBuilder.array([this.createEmailFormGroup()])
  });
}

Step 2: Define a method to dynamically construct new FormGroup

private createEmailFormGroup(): FormGroup {
  return new FormGroup({
    'emailAddress': new FormControl('', Validators.email),
    'emailLabel': new FormControl('')
  })
}

Step 3: Define a method to dynamically add new FormGroup to the FormArray

public addEmailFormGroup() {
  const emails = this.emailForm.get('emails') as FormArray
  emails.push(this.createEmailFormGroup())
}

Step 4 (Optional): Define method to delete FormGroup

public removeOrClearEmail(i: number) {
  const emails = this.emailForm.get('emails') as FormArray
  if (emails.length > 1) {
    emails.removeAt(i)
  } else {
    emails.reset()
  }
}

Step 5: Create the HTML form template

<form [formGroup]="emailForm">
  <div formArrayName="emails">
    <div class="row" *ngFor="let email of emailForm.get('emails').controls; let i = index"
        [formGroupName]="i">

Note that within the formArrayName element, the dynamic email FormGroups are named based on the array index.

Final Form

<mat-toolbar color="primary">
    Angular Form Demo - Dynamically add form controls
</mat-toolbar>

<form class="basic-container" [formGroup]="emailForm">
  <div formArrayName="emails">
    <div class="row" *ngFor="let email of emailForm.get('emails').controls; let i = index"
        [formGroupName]="i">

      <div class="col-1">
        <mat-icon class="mt-3">email</mat-icon>
      </div>

      <mat-form-field class="col-4">
        <input matInput formControlName="emailAddress" placeholder="Email" autocomplete="email">
        <mat-error *ngFor="let validation of validationMsgs.emailAddress">
          <div *ngIf="email.get('emailAddress').hasError(validation.type)">
            {{validation.message}}
          </div>
        </mat-error>
      </mat-form-field>

      <mat-form-field class="col-4">
        <mat-label>Label</mat-label>
        <mat-select formControlName="emailLabel">
          <mat-option *ngFor="let label of emailLabels" [value]="label">
            {{label}}
          </mat-option>
        </mat-select>
      </mat-form-field>

      <div class="col-3">
        <button class="float-left" mat-icon-button color="primary" aria-label="Remove/clear"
            (click)="removeOrClearEmail(i)" matTooltip="Remove">
          <mat-icon>highlight_off</mat-icon>
        </button>
        <button class="float-left" mat-icon-button color="primary" aria-label="Add"
            (click)="addEmailFormGroup()" matTooltip="Add">
          <mat-icon>add_circle_outline</mat-icon>
        </button>
      </div>
    </div>
  </div>
</form>

Final Component

import {Component} from '@angular/core';
import {FormBuilder, FormArray, FormControl, FormGroup, Validators} from '@angular/forms';

@Component({
  selector: 'form-app',
  templateUrl: 'app.component.html'
})
export class AppComponent {
  public emailForm: FormGroup;
  public emailLabels = ['Home', 'Work', 'Other'];
  public validationMsgs = {
    'emailAddress': [{ type: 'email', message: 'Enter a valid email' }]
  }

  constructor(private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.emailForm = this.formBuilder.group({
      emails: this.formBuilder.array([this.createEmailFormGroup()])
    });
  }

  public addEmailFormGroup() {
    const emails = this.emailForm.get('emails') as FormArray
    emails.push(this.createEmailFormGroup())
  }

  public removeOrClearEmail(i: number) {
    const emails = this.emailForm.get('emails') as FormArray
    if (emails.length > 1) {
      emails.removeAt(i)
    } else {
      emails.reset()
    }
  }

  private createEmailFormGroup(): FormGroup {
    return new FormGroup({
      'emailAddress': new FormControl('', Validators.email),
      'emailLabel': new FormControl('')
    })
  }
}

这篇关于如何在Angular中单击按钮时将FormControl动态添加到FormArray?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 09:23