【问题标题】:How to make click event optional in an angular 2 *ngFor loop如何在 Angular 2 *ngFor 循环中使点击事件成为可选
【发布时间】:2020-11-21 01:21:57
【问题描述】:

我正在制作一个周历,用户可以在其中单击日历标题中的星期几以突出显示当天的事件:

<thead>
    <tr>
        <td *ngFor="let day of days | async"
            (click)="highlightWeek(day)">{{day.header}}</td>
    </tr>
</thead>

我想让它在给定日期没有事件时,那么当天的标题是不可点击的。这可以像这样在组件中完成:

highlightWeek(day) {
    if (day.events.length > 0) {
        ...

但是,如果我这样做,那么每当用户将鼠标悬停在空白的日期标题上时,浏览器仍会将光标的形式从箭头更改为手形。我只想在有事件的日子里有点击事件,所以这不会发生。像这样的:

<thead>
    <tr>
        <td *ngFor="let day of days | async"
            (if (day.events.length > 0)): (click)="highlightWeek(day)">{{day.header}}</td>
    </tr>
</thead>

但我不知道如何做到这一点。

【问题讨论】:

    标签: javascript angular onclick ngfor


    【解决方案1】:

    将循环放入 ng-container 中,然后您可以显示一个 td 如果它应该是可点击的,而另一个如果不是。像这样:

    <thead>
     <tr>
        <ng-container *ngFor="let day of days | async">
          <td (click)="highlightWeek(day)" style="cursor: pointer" *ngIf="day.events.length>0">
            {{day.header}}
          </td>
          <td *ngIf="day.events.length===0" style="cursor: default">{{day.header}}</td>
        </ng-container>
     </tr>
    </thead>
    

    【讨论】:

      【解决方案2】:

      光标变为pointer 是因为 CSS 规则,而不是因为您绑定了 click 事件。我想你想要这样的东西:

      <td *ngFor="let day of days | async" 
          [ngStyle]="{ 'cursor': day.events.length > 0 ? 'pointer' : 'default' }"
          (click)="day.events.length === 0 || highlightWeek(day)">
          {{day.header}}
      </td>

      【讨论】:

      • 这是一个聪明的解决方案!
      【解决方案3】:

      你可以简单地在 td 元素上绑定 disabled 属性,如下所示:

      <td *ngFor="let day of days | async"
                  (click)="highlightWeek(day)"
                  [disabled]='day.events.length > 0? null : true'>
          {{day.header}}
      </td>
      

      【讨论】:

        【解决方案4】:

        创建一个类以在没有事件时显示您想要的光标

        .no-events:hover{
            cursor:  not-allowed !important;
        }
        

        然后在您的模板中分配该类

        <thead>
           <tr>
               <td [class.no-evets]="day.events.length > 0" *ngFor="let day of days | async"
                (click)="highlightWeek(day)">{{day.header}}</td>
           </tr>
        </thead>
        

        使用该代码,您的函数将在点击时被调用,但光标将显示为您定义的。

        【讨论】:

          【解决方案5】:

          我今天遇到了这个internetzer's 解决方案,它有条件地阻止了对事件的调用。从逻辑上讲and 带有如下事件的条件:

          <td *ngFor="let day of days | async" 
            (click)="day.events.length > 0 && highlightWeek(day)">{{day.header}}</td>
          

          【讨论】:

            猜你喜欢
            • 2018-05-13
            • 1970-01-01
            • 2017-02-16
            • 2017-07-03
            • 1970-01-01
            • 2017-03-30
            • 1970-01-01
            • 2017-03-04
            • 2016-12-05
            相关资源
            最近更新 更多