【问题标题】:Angular : set reactive form with dynamic looping inputsAngular:使用动态循环输入设置反应形式
【发布时间】:2019-11-25 15:19:52
【问题描述】:

我必须为使用数据循环进行输入的表单设置反应式表单验证:

我的表单构建器如下所示:

constructor(private formBuilder: FormBuilder) { 
    this.userForm = this.formBuilder.group({
      'inputOne': ['', [Validators.required]],
      'inputOne': ['', [Validators.required]],
       ...
      'inputN': ['', [Validators.required]]
    });
  }

我的模板看起来像这样:

<form [formGroup]="userForm">
  <div class="form-group" *ngFor="let item of items; let i=index;">
        <label for="lastName">{{item.name}}</label>
        <input class="form-control" name="lastName" id="lastName" type="text" [formControlName]="item.name">
      </div>
</form>

从我的后端动态加载项目的位置

如何在 Angular 响应式表单中动态填充控件?

【问题讨论】:

    标签: javascript angular typescript angular-reactive-forms angular-forms


    【解决方案1】:

    听起来你想要一个表单数组,而不是一个组......

      constructor(private formBuilder: FormBuilder) { 
        // build an empty form array
        this.userForm = this.formBuilder.array([]); 
      }
    
      // call this whenever you need to add an item to your array
      private addItem(item) {
        // build your control with whatever validators / value
        const fc = this.formBuilder.control(i.lastName, [Validators.required]);
        this.userForm.push(fc); // push the control to the form
      }
    
      // call this function whenever you need to reset your array
      private resetFormArray(items) {
        this.userForm.clear(); // clear the array
        items.forEach(i => this.addItem(i)); // add the items
      }
    
    <form [formGroup]="userForm">
      <div class="form-group" *ngFor="let item of items; let i=index;">
        <label for="lastName">{{item.name}}</label>
        <input class="form-control" name="lastName" id="lastName" type="text" [formControlName]="i">
      </div>
    </form>
    

    请注意,您在此处使用表单控件名称的索引

    【讨论】:

    • 你知道如何从这个 HTML 模板中引用那种 FC 吗?比如让我们说如果formControlName="{{ i }}" 如何判断它的值是dirty 还是显示附加按钮的东西?
    • nvm,我喜欢 da wae - 我会把这个留给想知道这个的人,就像我一样:人们可以通过调用 userForm.get([i]) 来简单地实现这一点,并将其用作 ngIf 中的条件实例(*ngIf="userForm.get([i]).value !== ''")。希望这可以帮助某人
    猜你喜欢
    • 1970-01-01
    • 2020-09-27
    • 2018-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-04
    • 1970-01-01
    • 2017-11-13
    相关资源
    最近更新 更多