1

我需要一个表单中的 url 列表。一个中继场。像这样的东西: 中继器字段

我正在使用我这样初始化的 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>

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

4

1 回答 1

0

(假设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

于 2018-01-25T13:35:29.180 回答