【问题标题】:How to check if element exists in an Object?如何检查对象中是否存在元素?
【发布时间】:2019-10-12 22:39:15
【问题描述】:

如何使用 *ngIf 来检查一个元素是否存在于 Object 中?

.ts 文件

this.data = ["cat", "dog"];

我想在我的 html 文件中检查 cat 是否存在于对象 this.data 中。我可以用 *ngIf 做到这一点吗?

【问题讨论】:

  • 不在html文件中是什么意思?

标签: html ionic3 angular2-directives


【解决方案1】:

您可以在 ts 文件中创建一个函数来检查数组中是否存在所需的字符串:

doesExist(animal: string): boolean {
return this.data.includes(animal);
}

然后在你的 html 文件中调用它:

<div *ngIf="doesExist('cat')"> [...] </div>

【讨论】:

    【解决方案2】:
    <div *ngIf="data.includes('cat')">hello world</div>
    

    我希望这会有所帮助。

    【讨论】:

      【解决方案3】:

      您可以先使用 ngFor 来迭代循环中的每个元素,然后使用 ngIf 检查值是否存在。

      例如:

      <div *ngFor="let element of data">
          <div *ngIf="element.cat">
           </div>
      </div>
      

      另一种方法是为此设置单独的功能,但我认为这是一种简单的方法。希望对您有所帮助。:)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-25
        • 1970-01-01
        • 2011-06-12
        • 2017-09-17
        • 1970-01-01
        • 2011-07-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多