arrays - 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','','']]。
谢谢!
解决方案
你有一个数组数组,所以你需要使用 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-到内部数组
推荐阅读
- c++ - 当只有一个进程正在写入时,Posix 共享内存同步
- excel - Excel 的问题 - 第三方是否篡改了我的计算机?
- python - 我只能访问 Python 函数中返回的部分项目吗?
- javascript - 跨度在反应应用程序中堆叠在彼此之上而不是在彼此之下
- api-eveonline - 从 eve online 的文件位置获取用户详细信息,如登录时间、宇宙角色开启
- excel - 如何使用电源查询提取图像链接?
- angular - 在 Angular 中使用 Youtube 的 Javascript API
- c# - 在 Entity Framework Core 中使用多个值进行更新
- android-jetpack - 在 un-rotate 应用程序中是否必须使用 ViewModel
- sas - 错误:在表达式中找不到所需的运算符 (SAS)