Amrmsmb
Amrmsmb

Reputation: 1

How to change button state based on *ngIf

in the below code, i want to do the following

if index is equal to 0 the text of the button should be info and enabled

and

    if index is equal to 1 the text of the button should be INFO and disabled
    

please have a look at me attempt below and let me know the ansewer

code:

td *ngFor="let application of applications;let index=index">
    <p> 
        <button (click)="showInfoWindow(application)" class="btn btn-sm btn-primary"
        *ngIf = "index == 1; else INFO">info</button>
    </p>
    <ng-template #INFO disabled>
        INFO.
      </ng-template>
</td>

Upvotes: 0

Views: 2003

Answers (1)

Barremian
Barremian

Reputation: 31105

You could apply the condition using ternary operator for label and use [disabled] property to enable/disable the button. You could take advantage of 0 being falsy in JS.

Try the following

<td *ngFor="let application of applications; let index=index">
  <p> 
    <button (click)="showInfoWindow(application)" [disabled]="!!index" class="btn btn-sm btn-primary">
      {{ !!index ? 'INFO' : 'info' }}
    </button>
  </p>
</td>

Update: Using *ngIf

<td *ngFor="let application of applications;let index=index">
  <p> 
    <button *ngIf="index; else enabled" (click)="showInfoWindow(application)" disabled class="btn btn-sm btn-primary">
      INFO
    </button>
    <ng-template #enabled>
      <button (click)="showInfoWindow(application)" class="btn btn-sm btn-primary">
        info
      </button>
    </ng-template>
  </p>
</td>

Working example: Stackblitz

Update: debug current index

It's much easier and quicker to directly render the index in the template rather than to console.log the current index.

<td *ngFor="let application of applications; let index=index" style="padding: 5px; border-right: 1px solid #000000;">
  Current index: {{ index }}
  ...
</td>

If you however insist on printing into console, you could define a function in the controller and pass the current index to it using interpolation.

Controller

printIndex(index: number) {
  console.log(index);
}

Template

<td *ngFor="let application of applications; let index=index">
  {{ printIndex(index) }}
  ...
</td>

But beware: this might extremely misleading as the function will be triggered for each change detection cycle with default change detection strategy.

Upvotes: 1

Related Questions