【问题标题】:Issue in adding a control dynamically to a reactive form in Angular将控件动态添加到 Angular 中的响应式表单的问题
【发布时间】:2017-10-18 19:18:03
【问题描述】:

我正在研究 Angular Reactive 表单。我想动态地将控件添加到表单中。但是当我添加一个控件时,它第一次添加了 两次 我不知道为什么,后来它工作正常。这是代码:

<form [formGroup]="reviewForm" >        
    <span *ngIf="isClicked">              
        <div formArrayName="controlArray">
            <div 
              class="form-group"
              *ngFor="let control of reviewForm.get('controlArray').controls; let i = index">            
              <label>{{label}} </label>                                      
              <input 
                type="{{control.value}}"                       
                class="form-control"                                        
                [formControlName]="i" >                       
            </div>  
        </div>  
    </span>
    <button type="button" (click)="addControl()">Add</button>         
</form>

组件类代码,addControl()在添加按钮点击事件上调用:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {  
  reviewForm: FormGroup;
  inputArray: string[] = [
    'text', 'radio', 'checkbox', 'select', 'textarea', 'button'
  ];

  selectedControl: string = '';   
  isClicked:boolean= false;
  label: string;
  isRequired:boolean = false;
  placeHolderValue: string = "";
  ngOnInit(){
    this.reviewForm = new FormGroup({   
      // 'placeHolder' : new FormControl(null),   
      'controlArray': new FormArray([
        new FormControl(null)
    ])
    });
  }

  addControl(){    
      this.isClicked = true;
      const control = new FormControl(this.selectedControl);
      (<FormArray>this.reviewForm.get('controlArray')).push(control);      
      // console.log(this.selectedControl);      
    }  

  onSubmit(){
    console.log(this.reviewForm);
  }
}

【问题讨论】:

  • 你能显示你的ts代码的其余部分吗?
  • 感谢您的回复@Med_Ali_Rachid,我已经添加了 ts 代码的其余部分。

标签: angular angular-reactive-forms


【解决方案1】:

发生的事情非常正常,因为当你的组件被创建时,isClicked = false 和你的formArray 已经包含了一个FormControl,由于这种情况而没有在开头显示:@ 987654324@

当您向 FormArray 添加新控件时,现在它包含两个 FormControls 和 isClicked 变为 true ,并显示两个 formControl

这是这种行为的原因

希望对你有帮助:)

【讨论】:

  • 没错,这就是问题所在。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-03
  • 1970-01-01
  • 2019-01-26
  • 2019-02-13
  • 1970-01-01
  • 1970-01-01
  • 2018-02-24
相关资源
最近更新 更多