【问题标题】:TypeScript error- This condition will always return 'false' since the types 'boolean' and 'string' have no overlapTypeScript 错误 - 此条件将始终返回 'false',因为类型 'boolean' 和 'string' 没有重叠
【发布时间】:2021-07-29 09:22:54
【问题描述】:

我在ng-container 中添加ngIf 条件,如果条件满足则display the component

我面临的问题是我收到错误

 This condition will always return 'false' since the types 'boolean' and 'string' have no overlap.

当我将条件设置为(当我使用not operator after &&)时

<ng-container *ngIf="data.dataClass === 'Dokes'
       && !data.dataSubclass === 'Land'"> ------------------>   NOT OPERATOR

但是当我删除 &amp;&amp; !data.dataSubclass === 'Land' 中的! 运算符时,代码可以正常工作

我不知道为什么它给了我这个错误。我想将! 运算符添加为I want to display component when data.dataSubclass is not equal to 'Land'

.html 文件

  <div>
      <ng-container *ngIf="data.dataClass === 'Dokes' 
       && !data.dataSubclass === 'Land'">-----------------------------> ERRORRR

!----- BELOW IS THE COMPONENT TO DISPLAY IF ABOVE CONDITION IS TRUE---------!
          <money-property name="Pika" [model]="data.pika"
                    [editMode]="!!dataEditService.editMode">
      <dl>
        <dd *ngFor="let d of data.pika; index as i">
          <edit-link dataClass="Dokes" 
                     [(selectedElement)]="data.pika[i]" [editMode]="!!dataEditService.editMode"></edit-link>
        </dd>
        
      </dl>
    </money-property>
  </ng-container>
  </div>

【问题讨论】:

    标签: html angular typescript angular-ng-if


    【解决方案1】:

    添加! 会抛出您尝试实现的逻辑,因为它会否定它右侧的值。这个:

    && !data.dataSubclass === 'Land'
    

    等价于

    && (!data.dataSubclass) === 'Land'
    

    这当然没有意义 - 布尔值永远无法与 'Land' 进行比较。你需要:

    && !(data.dataSubclass === 'Land')
    

    但更清晰的方法是:

    && data.dataSubclass !== 'Land'
    

    【讨论】:

    • 谢谢,我会试试的,如果我想再添加一个条件I want to display component when data.dataSubclass is not equal to 'Land' OR when not equal to Water,还有一个问题是什么好方法。 note 的一件事是 data.dataSubclass 一次可以有一个值,对于不同的记录,它将是 LandWater。我相信我应该使用&amp;&amp; 运算符,对吧?
    • !['Land', 'Water'].includes(data.dataSubclass)?
    • 我正在使用 Angular,上面的代码将在 html 文件中
    • 这应该不是问题吧?您仍然可以在 ngIf 中使用普通 JavaScript
    • 啊哈聪明!我以为这行不通。它做了。谢谢
    猜你喜欢
    • 2020-01-05
    • 2019-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-26
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    相关资源
    最近更新 更多