* ngFor循环ul列表根据模型值分类

时间:2019-02-18 01:56:42

标签: angular

假设我有模特:

export class CarDetails {
    Name: string;
    Favourite: boolean;
}

我有一个对象数组:

[{
  Name: "Toyota",
  Favourite: false
},{
  Name: "Skoda",
  Favourite: true
},
{
  Name: "Volvo",
  Favourite: true
},{
  Name: "Honda",
  Favourite: false
}]

我的目标是以这种方式用数组创建循环:

===Favourite===
Skoda
Volvo
===Other===
Honda
Toyota

在代码中,它应如下所示:

<ul>
    <div>Favourite</div>
    <li>Skoda</li>
    <li>Volvo</li>
    <div>Other</div>
    <li>Honda</li>
    <li>Toyota</li>
</ul>

有什么办法可以用角度* ngFor循环来做到这一点吗?我发现了一些有关templateOutlets的信息,但在我的示例中却无效,这是代码:

<ul #carList>
  <div>Favourite</div>
  <div *ngTemplateOutlet="favourite"></div>
  <div>Other</div>
  <div *ngTemplateOutlet="other"></div>

  <ng-container *ngFor="let data of Cars;let i = index;">
    <ng-template #favourite> // how to make the this in dynamic way - if favourite, then favourite, else other
      <li>{{data.name}}</li>
    </ng-template>
  </ng-container>
</ul>

另一种方法是拥有两个列表,但是我不希望维护两个相似的对象,尤其是如果我想添加一些过滤器等,则会变得很复杂。

2 个答案:

答案 0 :(得分:0)

我建议您使用*ngIf并用<ng-container>进行迭代

<ul>
  <div>Favourite</div>
  <ng-container *ngFor="let data of Cars">
    <li *ngIf="data.Favourite === true">
      {{data.Name}}
    </li>
  </ng-container>

  <div>Other</div>
  <ng-container *ngFor="let data of Cars">
    <li *ngIf="data.Favourite === false">
      {{data.Name}}
    </li>
  </ng-container>
</ul>

答案 1 :(得分:0)

您可以在此StackBlitz中看到实现。

export class AppComponent {
  name = 'Angular';

  readonly cars = [{
    Name: "Toyota",
    Favourite: false
  }, {
    Name: "Skoda",
    Favourite: true
  },
  {
    Name: "Volvo",
    Favourite: true
  }, {
    Name: "Honda",
    Favourite: false
  }];

  favoriteCars = this.cars.filter((a) => a.Favourite);
  nonFavoriteCars = this.cars.filter(a => !a.Favourite);
}


<div>
  ==favorites==
  <ul *ngFor="let car of favoriteCars">
    <li>{{car.Name}}</li>
  </ul>
  ==Other==
  <ul *ngFor="let car of nonFavoriteCars">
    <li>{{car.Name}}</li>
  </ul>
</div>

结果:

==favorites==
Skoda
Volvo
==Other==
Toyota
Honda