代码之家  ›  专栏  ›  技术社区  ›  NDDT

URL中继器字段,带角度5和FormControls的FormArray

  •  1
  • NDDT  · 技术社区  · 7 年前

    我需要一个表单中的URL列表。中继器场。类似这样: repeater field

    我使用的是一个FormGroup,我这样初始化它:

    this.myForm = this.fb.group({
        otherField: ['', Validators.required],
        urls: this.fb.array([
            new FormControl('test'),
            new FormControl('test2')
        ]),
    .
    .
    .
    });
    

    一些getter方法:

      private get urls() { return this.myForm .get('urls'); }
      private get otherField() { return this.myForm .get('otherField'); }
    

    在HTML方面,它如下所示:

    <form [formGroup]="myForm">
      <div class="form-row">
        <div class="col mb-3">
          <input type="text" class="form-control" formControlName="otherField">
        </div>
      </div>
      <div class="form-row">
        <div class="col mb-3" formArrayName="urls">
          <div class="input-group" *ngFor="let item of urls.controls; let i = index" >
            <input type="text" class="form-control" formControlName="???">
            <div class="input-group-append">
              <button class="btn btn-outline-secondary" type="button">
                <i class="fas fa-plus"></i>
               </button>
             </div>
           </div>       
         </div>
       </div>
    </form>
    

    这已经显示了正确的输入量(在这个最小的示例中为两个)。但是如何将日期绑定到输入?我可以使用什么作为FormControlName?

    1 回复  |  直到 7 年前
        1
  •  0
  •   AT82    7 年前

    (假设 urls2 是输入错误)

    因为我们处理的是单个表单控件,所以我们可以使用迭代的索引值来引用表单控件,所以只需添加 [formControlName]="i" 对于您的输入:

    <div class="col mb-3" formArrayName="urls">
      <div class="input-group" *ngFor="let item of urls.controls; let i = index" >
        <input type="text" class="form-control" [formControlName]="i">
       </div>       
     </div>
    

    StackBlitz