在Angular 6中显示逗号分隔的字符串

时间:2018-10-05 09:24:58

标签: html angular typescript loops twig

我正在尝试遍历Angular 6中逗号分隔的字符串。

public  getCategory(){
    this.Jarwis.getCategorys().subscribe((data:  Array<object>) => {
    this.categorys  =  data;
    console.log(this.categorys);
});

这是我的功能,其控制台日志为

(3) [{…}, {…}, {…}, {…}, {…}, {…}]
 0: {id: 4, category_name: "Agriculture", sub_category_names: "Other Agriculture,Vineyards and Wineries,Greenhouses,Tree Farms and Orchards"}
 1: {id: 5, category_name: "Automotive and Boat", sub_category_names: "Auto Repair and Service Shops,Car Dealerships,Marine/Boat Service and Dealers,Junk and Salvage Yards"}
 2: {id: 13, category_name: "Beauty and Personal care", sub_category_names: "Massage,Tanning Salons,Spas,Hair Salons and Barber Shops"}

我可以借助

在视图页面中显示类别名称
<li *ngFor='let category of categorys'>
  <div>{{ category.category_name }}</div>
</li>

但是我怎么能在这样的不同div中显示sub_category_names

<div> subcategory_name1 </div>
<div> subcategory_name2 </div>

请帮助

4 个答案:

答案 0 :(得分:2)

您可以使用自定义管道拆分数组:

@Pipe({
  name: 'splitComma'
})
export class SplitCommaStringPipe implements PipeTransform {
  transform(val:string):string[] {
    return val.split(',');
  }
}

并像这样使用它:

<div *ngFor="let subcategory of category.sub_category_names|splitComma"> 
  {{subcategory}}
</div>

答案 1 :(得分:1)

在html中使用以下代码:

<li *ngFor='let category of categorys'>
  <div>{{ category.category_name }}</div>
  <div *ngFor="let subCategory of category.sub_category_names?.split(',')">
     {{ subCategory }}
  </div>
</li>

答案 2 :(得分:0)

也许您可以通过使用其他* ngFor

来尝试这种方式
<li *ngFor='let category of categorys'>
    <div *ngFor="let subCategory of (category.sub_category_names.split(','))">{{ subCategory }}</div>
</li>

https://stackblitz.com/edit/angular-a4s1bq

答案 3 :(得分:0)

您还可以在返回数据时拆分子类别。然后在子类别上使用*ngFor。在ES6中,它看起来像这样:

this.categories = data.map((e => {
  return {
     ...e,
     sub_category_names: e.sub_category_names.split(',')
  }
}));

顺便说一句。类别的复数是类别

https://stackblitz.com/edit/js-rkkyjs