【问题标题】:Angular see if String is Within Another String, using Substring and ngIfAngular 使用 Substring 和 ngIf 查看字符串是否在另一个字符串中
【发布时间】:2020-02-28 22:11:04
【问题描述】:

我正在执行以下操作,试图检查 addressDescription 是否包含单词 Maple street。 收到以下错误,如何解决?

<app-address-mailing *ngIf="message.addressDescription.indexOf('Maple') > -1"></app-address-mailing>

AddressMailingComponent.html:21 ERROR TypeError: Cannot read property 'indexOf' of undefined

下面的资源无法正常工作,加上它的旧语法是 ngIf 而不是 ng-if

ng if with angular for string contains

【问题讨论】:

  • 尝试*ngIf="message.addressDescription?.indexOf('Maple') 使用可为空的运算符
  • hi @terahertz 嗯,摆脱了编译错误,现在它渲染了 html 项,即使 Maple 不存在,我只是尝试了 -1"> ,并在没有真正检查 if 语句的情况下显示,奇怪

标签: javascript html css angular angular8


【解决方案1】:

正如错误提示:

message.addressDescription 未定义。

所以你可以添加一个新的条件:

*ngIf="message?.addressDescription && message.addressDescription.indexOf('Maple') > -1"

有了这个条件,你就可以确定它是有效的。

【讨论】:

    【解决方案2】:

    消息未定义,先检查再使用includes

    如果addressDescription是一个句子,试试下面的

    <app-address-mailing *ngIf="message?.addressDescription.split(' ').includes('Maple')"></app-address-mailing>
    

    否则,请尝试以下操作

    <app-address-mailing *ngIf="message?.addressDescription.includes('Maple')"></app-address-mailing>
    

    不用说:你可以申请toLowerCase方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-11
      • 1970-01-01
      • 2019-03-23
      • 1970-01-01
      • 2011-02-07
      • 1970-01-01
      • 2011-03-24
      相关资源
      最近更新 更多