【问题标题】:How to compare 2 dynamic values in ngIf如何比较 ngIf 中的 2 个动态值
【发布时间】:2019-10-01 07:39:04
【问题描述】:

我是 Angular 的新手, 试图在 ngIf 中比较 Json 的 2 个属性值,

我的地址对象具有以下属性 Line1、Line2、城市、县、邮政编码、国家

我想在 UI 上显示县值,如果县不等于城市,

我正在使用 Angular 7

数据库上的示例地址1:

  • 第 1 行:abc123
  • 第 2 行:xyz
  • 城市:伦敦
  • 县:伦敦
  • 国家:英国

由于县值等于城市值 在我要显示的 UI 上:

  • abc123,xyz,伦敦,英国

数据库上的示例地址2:

  • 第 1 行:asdf456
  • 第 2 行:lkj
  • 城市:伦敦
  • 县:qwerty
  • 国家:英国

由于县值不等于城市值 在我要显示的 UI 上:

  • asdf456, lkj, 伦敦, qwerty, 英国

所以尝试下面的代码,但它不工作。

<div *ngIf="address.city == address.county">{{address.county}}</div>

用单引号试过

<div *ngIf="'address.city' == 'address.county'">{{address.county}}</div>

三个等于'==='

<div *ngIf="address.city === address.county">{{address.county}}</div>

提前致谢

【问题讨论】:

  • 嗨!欢迎来到 StackOverflow。您需要添加一个minimal reproducible example。仅凭这一点还不足以说明问题所在。如果 address 定义正确,您提供的第一个和第三个解决方案应该可以工作。另一方面,第二种解决方案只是两个不同的字符串,它们相互比较总是等于false
  • 看起来您正试图显示县 与城市相同。改用!== 运算符:<div *ngIf="address.city !== address.county">{{address.county}}</div>

标签: angular


【解决方案1】:

如果它是动态的,比如 Observable 等:

<div *ngIf="address$ | async as address">
    <div *ngIf="address.city  == address.county">{{address.county}}</div>
</div>

| async 是动态值 Observables 和 Promises 的管道。小提示尽量不要在 *ngFor 循环中使用这个管道。

【讨论】:

    猜你喜欢
    • 2016-09-15
    • 2018-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-22
    • 2022-11-13
    • 2016-03-03
    • 1970-01-01
    相关资源
    最近更新 更多