Search code examples
javascriptangularonclickngfor

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


I am making a weekly calendar, where users can click the days of the week in the calendar header to highlight the events on that day:

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

I would like to make it so that when there are no when there are no events on a given day, then the header for that day is not clickable. This could be done in the component like so:

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

But if I do this, then the browser still changes the form of the cursor from the arrow to the hand, whenever the user hovers over the empty day headers. I would like to only have the click event on the days where there are event, so this doesn't happen. Something like this:

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

But I don't know how to accomplish that.


Solution

  • Put the loop in an ng-container and then you can have one td displaying if it should be clickable and another if not. Like this:

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