繁体   English   中英

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

[英]Displaying comma separated string in 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>

请帮忙

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

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

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

也许你可以通过使用额外的* 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

您还可以在返回数据时拆分子类别。 然后在子类别上使用*ngFor 在ES6中,这将是这样的:

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

顺便说一句。 多个类别是类别

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM