如何在不首先执行 *ngFor 的情况下在对象上使用 *ngIf 来检查键是否具有特定值?

How to use *ngIf on an object to check if key has a specific value without doing *ngFor firstly?

我想做的是仅在使用 *ngIf 的情况下显示 HTML 中的第一行(在下面的代码中)。我已经完成了基本验证,但我遇到了困难,无法找到如何 *ngIf 直接访问对象键(并且之前不使用 *ngFor,在不同的元素上)。我想做的是仅在 object.key === 'specific value' 时显示该行。我已经尝试过使用“键”、“对象”的选项,但似乎没有任何效果。如果你们有任何建议,我将不胜感激。

我的HTML

<ion-grid *ngIf="!isLoading && loadedBio.length > 0">
<ng-container *ngFor="let bio of loadedBio">
  <ng-container *ngIf="bio.category === '1'">
    <ion-row class="ion-padding">
      <ion-col>
        <ion-list class="no-last-border">
          <ion-item
            detail="false"
            *ngIf="bio.category === '1'">
            <ion-label
              [ngStyle]="{
                color:
                  bio.category === '1'
                    ? '#A34F83'
                    : 'var(--ion-color-secondary)'
              }"
              class="bioLabel"
              >{{bio.friendlyName}}</ion-label>
          </ion-item>
        </ion-list>
      </ion-col>
    </ion-row>
  </ng-container>
</ng-container>

我想从中访问密钥的 JS 对象具有以下格式

loadedBio = [{key: value, key2: value}]

如果您需要显示找到的对象的每个属性,那么,在您的组件中,您需要先将该找到的对象转换为数组 - 其中数组中的每个元素代表一个 属性 在对象上,然后遍历它以显示每个元素:

const obj1 = {
  a: 'a title',
  b: 42,
  c: false
};

const arr1 = Object.values(obj1);

放在一起看起来像这样。首先,在组件中:

import { Component } from '@angular/core';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

   loadedBio = [{'key': 1, 'key2': 2}, {'key': 3, 'key2': 4}];

   obj1 = {
     a: 'a title',
     b: 42,
     c: false
   };

  arr1 = Object.values(this.obj1);

  constructor() {

  }

}

并且在视图中:

<ion-header>
  <ion-navbar>
    <ion-title>Home</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <ng-container *ngIf="loadedBio">
    <ion-list *ngFor="let bio of loadedBio">
      <ng-container *ngIf="bio.key === 1">
         <ion-item>{{bio.key}}</ion-item>
      </ng-container>
    </ion-list>
  </ng-container>

  <ng-container *ngFor="let e of arr1">
    <ion-item>{{e}}</ion-item>
  </ng-container>

</ion-content>

这应该能让您了解如何处理您的情况。听起来您想转换组件中的数据,然后迭代它需要在您的视图中。

这是工作中的 link StackBlitz:

最好像这样在控制器中过滤数组

this.filteredBio = this.loadedBio.filter(el=>el.category === 'overall')

然后简单地在这个 filteredBio 数组上使用 *ngFor。这将只有类别为 'overall'

的对象

另一种解决方案是实现自定义管道