Angular:如何在单击按钮时将FormControl动态添加到FormArray

时间:2019-11-25 14:07:19

标签: angular angular-forms

click to open image related to problem

如何在formarray中动态添加formcontrol(option)?我想添加问题formarray。单击按钮应显示。我正在使用角度7。

//ngOnInit creating form
    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代码。我想在单击按钮时动态添加表单控件选项,并且表单控件应位于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>

1 个答案:

答案 0 :(得分:0)

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

该演示具有以下依赖性:角度8,Angular MaterialBootstrap 4

最终结果(Stackblitz Demo

Angular Form Demo - dynamically add form controls

步骤1:定义表单模型

n_clusters

步骤2:定义一种方法来动态构建新的constructor(private formBuilder: FormBuilder) { } ngOnInit() { this.emailForm = this.formBuilder.group({ emails: this.formBuilder.array([this.createEmailFormGroup()]) }); }

FormGroup

步骤3:定义一种方法,将新的private createEmailFormGroup(): FormGroup { return new FormGroup({ 'emailAddress': new FormControl('', Validators.email), 'emailLabel': new FormControl('') }) } 动态添加到FormGroup

FormArray

步骤4(可选):定义删除public addEmailFormGroup() { const emails = this.emailForm.get('emails') as FormArray emails.push(this.createEmailFormGroup()) }

的方法
FormGroup

第5步:创建HTML表单模板

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

请注意,在<form [formGroup]="emailForm"> <div formArrayName="emails"> <div class="row" *ngFor="let email of emailForm.get('emails').controls; let i = index" [formGroupName]="i"> 元素内,动态电子邮件formArrayName是根据数组索引命名的。

最终形式

FormGroups

最终组件

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