简体   繁体   English

如何在 Angular 中使用 ngFor 仅显示某些数据类型?

[英]How do I display only certain data types with ngFor in Angular?

I'm iterating over the array called "fruits", containing objects of type "FruitService" - a class I defined and want to display each element, but after deleting them (I realize this is weird-no db) they become of type "undefined" contaminating my array.我正在遍历名为“fruits”的数组,其中包含“FruitService”类型的对象 - 我定义并想要显示每个元素的 class,但在删除它们之后(我意识到这很奇怪 - 没有 db)它们变成了“ undefined” 污染了我的数组。 I don't want these to display (they show up as blank) so I want to display only "FruitService" objects.我不希望这些显示(它们显示为空白)所以我只想显示“FruitService”对象。 How do I do that?我怎么做?

<ul>

<li *ngFor="let fruit of fruits">
{{ fruit.name }}  price: {{ fruit._price }}   qty: {{ fruit.qty }}

</ul>

You can either filter them with a pipe or by checking if they are truthy:您可以使用 pipe 过滤它们,也可以检查它们是否真实:

<ul>
  <ng-container *ngFor="let fruit of fruits">
    <li *ngIf="!!fruit">
      {{ fruit.name }}  price: {{ fruit._price }}   qty: {{ fruit.qty }} 
    </li>
  <ng-container>
</ul>

Solution with a pipe:使用 pipe 的解决方案:

<ul>
  <ng-container>
    <li *ngFor="let fruit of fruits | defined">
      {{ fruit.name }}  price: {{ fruit._price }}   qty: {{ fruit.qty }} 
    </li>
  <ng-container>
</ul>
@Pipe({
  name: 'defined'
})
export class DefinedPipe implements PipeTransform {
  transform(array: any[]): any[] {
    return array.filter(element => !!element);
  }
}

This issue is better handled off in the controller.这个问题在 controller 中得到了更好的处理。 Ideally, there should be no undefined elements in the array when the corresponding element is removed.理想情况下,删除相应元素时,数组中不应有undefined的元素。 They should actually be removed from the array.它们实际上应该从数组中删除。

That said, you could do a simple check in the template to see if the element is defined before rendering them也就是说,您可以在模板中进行简单的检查,以查看元素是否在渲染之前定义

<ul>
  <ng-container *ngFor="let fruit of fruits">
    <li *ngIf="fruit">
      {{ fruit.name }}  price: {{ fruit._price }}   qty: {{ fruit.qty }}
    </li>
  </ng-container>
</ul>

The ng-container tag would be commented out in the final DOM and won't generate additional elements. ng-container标签将在最终的 DOM 中被注释掉,并且不会生成额外的元素。

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

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