首页 > 解决方案 > Angular - 将数组存储到表单数组中

问题描述

这是我在这里的第一个问题。由于我是法国人,我希望你能理解 :D 而且这并不容易解释。两周前我开始学习 Angular。只是让你知道...

这是关于音频专辑(EP、CD)的集合。这是JS接口:

export interface Album {
    id: number;
    artist: string;
    title: string;
    year: number;
    cover: string;
    tracks: [string, string][]; //[title, duration]
}

我尝试构建一个响应式表单以将新专辑添加到不应修改的现有数组中。所以 track 属性不能是对象数组。它必须是一个字符串元组数组。例如:

{
    id: 5,
    artist: ' Dntel',
    title: 'Life Is Full Of Possibilities',
    year: 2001,
    cover: 'R-16855-1196613859.jpg',
    tracks: [
      ['Umbrella', '4:43'],
      ['Anywhere Anyone', '4:37'],
      ...
    ]
}

组件中的表单:

export class AddAlbumComponent implements OnInit {
  albumForm: FormGroup = this.fb.group({
    artist: ['', Validators.required],
    title: ['', Validators.required],
    year: ['', Validators.required],
    cover: [''],
    tracks: this.fb.array([
      this.fb.group(
        [
          this.fb.control(''), // title input
          this.fb.control('')  // duration input
        ]
      )
    ])
  });
}

实际的形式是这样的(对不起,界面是法语的): reactive form

现在我的问题是:如何将每首曲目的标题和持续时间存储在我的表单中?

我试过了:

<input type="text" id="title" [formControlName]="tracks.at(i,0)">
<input type="text" id="duration" [formControlName]="tracks.at(i,1)">

但是数组只包含空字符串:[['0','',''],['1','','']]。

谢谢!

标签: arraysangularformstuples

解决方案


你有一个数组数组,所以你需要使用 FormArray 的 FromArray

albumForm: FormGroup = this.fb.group({
    artist: ['', Validators.required],
    title: ['', Validators.required],
    year: ['', Validators.required],
    cover: [''],
    tracks: this.fb.array([
      this.fb.array(  //<--this is fb.array
        [
          this.fb.control(''), // title input
          this.fb.control('')  // duration input
        ]
      )
    ])
  });

为了避免生产中的问题,您声明了两个辅助函数

  get tracks()
  {
    return this.albumForm.get('tracks') as FormArray
  }
  getTrack(i)
  {
    return (this.albumForm.get('tracks') as FormArray).at(i) as FormArray
  }

而你 .html

<form [formGroup]="albumForm">
    <div *ngFor="let tracks of tracks.controls;let i=index" >
        <input [formControl]="getTrack(i).at(0)">
        <input [formControl]="getTrack(i).at(1)">
    </div>
</form>

看到我们直接使用formControl-而不是formControlName-到内部数组

堆栈闪电战


推荐阅读