如何在 angular 2 *ngFor 循环中使点击事件可选

How to make click event optional in an angular 2 *ngFor loop

我正在制作周历,用户可以点击日历中的星期几 header 以突出显示当天的事件:

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

我想做到这一点,当某一天没有事件时,那一天的 header 不可点击。这可以像这样在组件中完成:

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

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

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

但我不知道如何实现。

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

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

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

<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>

将循环放在一个 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>

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

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

然后在您的模板中分配 class

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

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

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

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