我有一个按钮列表,需要根据条件启用/禁用,一次可能会禁用两个或三个按钮。
<li *ngFor="let button of buttons; let i = index">
<button *ngIf="disableButtonIndex && i+1 == disableButtonIndex" class="btn btn-lg btn-primary" disabled> {{ button.title }}</button>
<button *ngIf="!(disableButtonIndex && i+1 == disableButtonIndex)" (click)="callAction(button.actionName || i)" class="btn btn-lg btn-primary">{{ button.title }}</button>
</li>
.ts
this.disableButtonIndex = 1;
上面的代码可以很好地禁用单个按钮,我如何禁用两个/更多按钮
最佳答案
您可以使用数组来保存禁用的索引或在按钮选项中添加禁用标志。
使用禁用的数组
https://stackblitz.com/edit/angular-sef3nc?file=src%2Fapp%2Fapp.component.html
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
disabledButtons= [1, 2]
buttons = [
{
actionName: 'action1',
title: 'button1'
},
{
actionName: 'action2',
title: 'button2'
},
{
actionName: 'action3',
title: 'button3'
}
]
callAction(action) {
console.log(action)
}
}
<li *ngFor="let button of buttons; let i = index">
<button class="btn btn-lg btn-primary"
[disabled]="disabledButtons.indexOf(i) !== -1"
(click)="callAction(button.actionName)">
{{ button.title }}
</button>
</li>
在选项中使用标志
https://stackblitz.com/edit/angular-zvbepr?file=src%2Fapp%2Fapp.component.html
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
buttons = [
{
actionName: 'action1',
title: 'button1',
disabled: true
},
{
actionName: 'action2',
title: 'button2',
disabled: true
},
{
actionName: 'action3',
title: 'button3',
disabled: false
}
]
callAction(action) {
console.log(action)
}
}
<li *ngFor="let button of buttons; let i = index">
<button class="btn btn-lg btn-primary"
[disabled]="button.disabled"
(click)="callAction(button.actionName)">
{{ button.title }}
</button>
</li>
关于javascript - 以 ngIf 为条件禁用/启用 ngFor 内的多个按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60824359/