angular - 与 ngIf 绑定(bind)

标签 angular typescript

我正在尝试根据 *ngIf 中提到的条件绑定(bind)值。当我在 *ngIf 中尝试 && 运算符时,它的工作很神秘。

代码

       <div *ngIf="days.sunday == true">
          <p class="circle ml-3">Sun</p>
        </div>
        <div *ngIf="days.monday == true">
          <p class="circle ml-2">Mon</p>
        </div>
        <div *ngIf="days.tuesday == true">
          <p class="circle ml-2">Tue</p>
        </div>
        <div *ngIf="days.wednesday == true">
          <p class="circle ml-2">Wed</p>
        </div>
        <div *ngIf="days.thursday == true">
          <p class="circle ml-2">Thu</p>
        </div>
        <div *ngIf="days.friday == true">
          <p class="circle ml-2">Fri</p>
        </div>
        <div *ngIf="days.saturday == true">
          <p class="circle ml-2">Sat</p>
        </div>

以上条件运行良好。我可以相应地打印这些值。

   <div *ngIf="days.sunday == true && days.monday == true  && days.tuesday  == true && days.wednesday  == true && 
   days.thursday  == true && days.friday == true &&  days.saturday == true">
            <p class="circle ml-2">Everyday</p>
                </div>

根据上述情况,如果所有条件都为真,我正在尝试打印 Everyday 但我正在打印 sun mon tue wed thu fri sat Everyday

最佳答案

使用 If/Else 模板

  • 检查是否所有日期都为真。然后你只打印 Everyday
  • Else根据自己的情况打印其他日子

<!-- If block for "Everyday" -->
<div *ngIf="days.sunday && days.monday && days.tuesday && days.wednesday && 
   days.thursday && days.friday && days.saturday; else elseBlock">
    <p class=" circle ml-2 ">Everyday</p>
</div>

<!-- Else block for other days "Sun, Mon, etc..." -->
<ng-template #elseBlock>
    <div *ngIf="days.sunday">
        <p class="circle ml-3">Sun</p>
    </div>
    <div *ngIf="days.monday">
        <p class="circle ml-2">Mon</p>
    </div>
    <div *ngIf="days.tuesday">
        <p class="circle ml-2">Tue</p>
    </div>
    <div *ngIf="days.wednesday">
        <p class="circle ml-2">Wed</p>
    </div>
    <div *ngIf="days.thursday">
        <p class="circle ml-2">Thu</p>
    </div>
    <div *ngIf="days.friday">
        <p class="circle ml-2">Fri</p>
    </div>
    <div *ngIf="days.saturday">
        <p class="circle ml-2">Sat</p>
    </div>
</ng-template>

注意事项

days.sunday === true 等同于 days.sunday 因为它是一个 bool 值

关于angular - 与 ngIf 绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54761347/

相关文章:

angular - Angular 中的 Async/await 或 Observable

Angular Material - 设置调色板

forms - Ionic 2 - 如果没有互联网+有效表格,我如何禁用按钮

json - TypeScript 在对象数组上使用 forkJoin

javascript - 使用模块功能的提供程序创建作用域模块

angular - 将 Angular2 HTML 和 TypeScript 构建到单个文件

javascript - Angular 2 - 表单数据

带有 Auth0 路由错误 404 的 Angular 2

typescript - 我如何表达参数可以扩展 typescript 中的字符串列表?

javascript - 如何使用 Jquery 在 angular 5 上触发点击事件