【问题标题】:Angular - Storing an array into a form arrayAngular - 将数组存储到表单数组中
【发布时间】:2020-02-19 13:44:30
【问题描述】:

这是我在这里的第一个问题。因为我是法国人,我希望你能理解它: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','','']]。

谢谢!

【问题讨论】:

  • 哪个数组有那个空字符串?
  • 专辑数组中包含的曲目数组。

标签: arrays angular forms tuples


【解决方案1】:

你有一个数组数组,所以你需要使用 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-到内部数组

stackblitz

【讨论】:

  • 非常感谢埃利塞奥!!!你的版本就像一个魅力!您的 stackblitz 链接非常有帮助!我被困了 4 天。
猜你喜欢
  • 2012-01-13
  • 1970-01-01
  • 1970-01-01
  • 2016-06-28
  • 1970-01-01
  • 2018-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多