【问题标题】:How ngIf can validate multiple conditions in Angular Reactive FormsngIf 如何验证 Angular Reactive Forms 中的多个条件
【发布时间】:2021-04-13 22:56:20
【问题描述】:

您能否指导我如何在 Angular 9 中使用*ngIf 处理多种情况,如下所示。以下不适用于我。

*ngIf="abc !! xyz"

但是,它适用于像

这样的个人情况
*ngIf="abc" 

*ngIf="xyz"

TS 码是:

radioButtonChanged($event){
   let radioValue = event.target['value'];

   console.log(radioValue);
   if(radioValue =='abc'){
     this.abc = true;
     this.xyz = false;
   } else{
     this.abc=false;
     this.xyz = true;
   }      
}

【问题讨论】:

  • *ngIf="abc || xyz"
  • 对更复杂的情况使用函数。
  • @HDJEMAI:在默认 CD 策略的情况下,将函数绑定到指令将在每个更改检测周期触发它。不推荐。
  • 有些时候没有检测到变化,没用?
  • 这能回答你的问题吗? angular 4: *ngIf with multiple conditions

标签: angular angular-forms angular-ng-if


【解决方案1】:

您可以在这里使用 if-else 概念:

<div *ngIf="condition1; else condition2"></div>

<ng-template #condition2>
  <div> whatever </div>
</ng-template>

你使用它的方式; || 运算符将像 &amp;&amp; 一样作为二元运算符工作。这不是正确的做法。

方法2:

您可以在 component.ts 文件中检查您想要的所有条件,然后将您的条件结果分配给一个变量,并将其与*ngIf 绑定。

这会有点乏味,但 HTML 将保持干净。

【讨论】:

    【解决方案2】:

    你可以这样做

    // If you want both the conditions to be true 
    <div *ngIf="abc && xyz"> whatever </div>
    
    // If you want either of them to be true
    <div *ngIf="abc || xyz"> whatever </div>
    
    // If you want neither of them to be true
    <div *ngIf="!abc && !xyz"> whatever </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-09
      • 2021-08-30
      • 2020-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-20
      • 2019-03-07
      相关资源
      最近更新 更多