簡體   English   中英

如何基於 *ngIf 更改按鈕 state

[英]How to change button state based on *ngIf

在下面的代碼中,我想做以下

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

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

請看看我下面的嘗試,讓我知道答案

代碼

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>

您可以使用 label 的三元運算符應用條件,並使用[disabled]屬性來啟用/禁用按鈕。 您可以利用0在 JS 中是虛假的。

嘗試以下

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

更新:使用*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>

工作示例: Stackblitz

更新:調試當前索引

直接在模板中渲染索引而不是 console.log 當前索引要容易和快捷得多。

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

但是,如果您堅持打印到控制台,則可以在 controller 中定義 function 並使用插值將當前索引傳遞給它。

Controller

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

模板

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

但請注意:這可能會產生極大的誤導,因為 function 將在每個更改檢測周期使用默認更改檢測策略觸發。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM