【问题标题】:Conditional to toggle button display based on number of items有条件地根据项目数切换按钮显示
【发布时间】:2023-04-11 06:59:01
【问题描述】:

我有一个基于 HTML 中项目列表的 ngFor 显示按钮。该列表可以包含 0 个或多个项目。我想根据该列表中的项目数来切换显示附加按钮,例如如果列表中有 0 个项目,则不会显示该按钮;如果列表中有超过 0 个项目,则会显示该按钮。这是我的代码:

<div class="panel-body">
     <!--Panel Body-->
     <button *ngFor="#trainingItem of trainingItems" type="button" style="text-align:left; margin-right: 10px;" class="btn btn-secondary btn-block">
          <strong>Name: </strong> {{trainingItem.Name}}
          <strong>Location: </strong> {{trainingItem.LocationName}}
     </button>

     <!--This is the button I want to toggle based on the number of items-->
          <button type="button" class="btn btn-primary btn-block" style="background-color: #323232; margin-top: 10px">Start Training</button>
</div>

我知道我可以通过在我的 Typescript 类中创建一个函数来处理这个问题,该函数根据列表中的项目数切换一个值,但我想完全在 HTML 端处理这个问题并避免创建一个整个函数在另一个文件中。

【问题讨论】:

    标签: javascript html angularjs angular


    【解决方案1】:

    您应该能够检查ngIf 中的数组长度:

    <button *ngIf="trainingItems.length" ...>
    

    【讨论】:

      【解决方案2】:

      在 Angular 中,您可以使用 NgIf directive 显示/隐藏元素

      在你的情况下:

      <button *ngIf="trainingItems.length" type="button" class="btn btn-primary btn-block" style="background-color: #323232; margin-top: 10px">
        Start Training
      </button>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多