【问题标题】:Displaying comma separated string in Angular 6在Angular 6中显示逗号分隔的字符串
【发布时间】:2018-10-05 09:24:58
【问题描述】:

我正在尝试在 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>

请帮忙

【问题讨论】:

  • 您可能需要将您的sub_category_names 更改为数组

标签: html angular typescript loops twig


【解决方案1】:

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

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

【讨论】:

    【解决方案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>
    

    【讨论】:

    • 我不建议这样做。尤其是具有更复杂的功能......它将在每个变化检测周期上执行。管道解决方案更有效。 (blog.appverse.io/…)
    • @Andrew 更改检测仅在类别属性发生更改时触发。在这种情况下,更改检测将永远不会触发,因为没有任何事件会更改类别属性。同样,如果类别属性会发生变化,那么显然它将重新渲染和管道,或者这里使用的任何东西都会触发。我正在使用 Angular 2 的 ChangeDetection,此代码在任何情况下都有效,不会引起任何问题。
    • 你可以看到我的意思是:stackblitz.com/edit/… 打开控制台,看看 split 被调用了多少次。还单击按钮(没有任何变化),看看会发生什么!问题是 Angular 不知道 split 方法返回几乎相同的东西(它实际上每次都返回一个新数组)所以它必须调用它。
    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

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

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

      顺便说一句。 category的复数形式是categories

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

      【讨论】:

        猜你喜欢
        • 2014-09-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-21
        相关资源
        最近更新 更多