angular - Angular 基于 id 获取类别描述
问题描述
我正在编辑表格。我发送类别购买 ID,但在描述中的选项中显示它,如下所示:
新campaign.html
<mat-label>categories</mat-label>
<mat-select multiple formControlName="VehicleCategory">
<mat-option *ngFor="let item of categories" [value]="item.id">{{item.description}}</mat-option>
</mat-select>
</mat-form-field>
所以在编辑表单中,我在 id 中得到响应,而不是在这样的描述中:
vehicleCategory: "4,2,3"
但我得到这样的获取请求的类别:
this.campaignService.getCategories().subscribe((data: any[])=>{
this.categories = data;
})
这是每个类别都有一个 id 的响应:
description: "test"
id: 4
那么如何根据 id 将我的类别显示为描述?
编辑.html
<mat-form-field appearance="fill">
<mat-label>Categories</mat-label>
<mat-select multiple formControlName="VehicleCategory">
<mat-option *ngFor="let item of categories" [value]="item.id">{{item.description}}</mat-option>
</mat-select>
</mat-form-field>
编辑.ts
allCategories = [];
// get categories
this.campaignService.getCategories().subscribe((data: any[])=>{
this.allCategories = data;
const categoryIds = this.data.vehicleCategory.split(',') ?? [];
const categories = categoryIds.map(
id => this.allCategories.find(c => c.id === id)
);
});
this.editForm = this.fb.group({
id: this.data.id,
Name: this.data.name,
VehicleCategory: [categories],
});
解决方案
如果您获取所有类别并存储在 中allCategories
,那么您可以简单地将 categoryId 映射到类别对象:
const categoryIds = this.data.vehicleCategory.split(',') ?? [];
const categories = categoryIds.map(
id => this.allCategories.find(c => c.id === id)
);
this.editForm = this.fb.group({
id: this.data.id,
Name: this.data.name,
VehicleCategory: categories
});