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

新手上路,请多包涵

我试图在 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>

请帮忙

原文由 Ajzz 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 454
2 个回答

在您的 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>

原文由 Sandip Jaiswal 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

 @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>

原文由 Andrei Tătar 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题