如果列表/数组不为空,如何禁用 Angular 中的按钮?

How to disable button in Angular if list / array is not empty?

在我的组件中,我从我的服务获取数据:

ngOnInit() {
  this._sharedService.
    getReceiptItem().takeUntil(this.ngUnsubscribe).
    subscribe(products => this.receiptItems = products);
}

如果我的数组 this.receiptItems 有任何项目,我该如何禁用按钮?

我试过这样的事情:

 <div class="top-left">
    <button [disabled]="receiptItems.count>0" type="button" [routerLink]="['/administration']"><i class="fas fa-bars fa-fw"></i></button>
 </div>

但显然这不是解决方案..

谢谢

你可以试试length

component.ts

receiptItems:Array<any>;
ngOnInit() {
  this._sharedService.
    getReceiptItem().takeUntil(this.ngUnsubscribe).
    subscribe(products => this.receiptItems = products);
}

component.html

<div class="top-left">
    <button [disabled]="receiptItems.length > 0" type="button" [routerLink]="['/administration']"><i class="fas fa-bars fa-fw"></i></button>
 </div>

您需要 Array.length 在 javascript

   <button [disabled]="receiptItems.length>0" type="button" [routerLink]="['/administration']"><i class="fas fa-bars fa-fw"></i></button>

使用以下内容更新您的代码:

<div class="top-left">
    <button [disabled]="receiptItems && receiptItems.length>0" type="button" [routerLink]="['/administration']"><i class="fas fa-bars fa-fw"></i></button>
 </div>
<button *ngIf="receiptItems!=undefined" [disabled]="receiptItems.length>0" type="button" [routerLink]="['/administration']"><i class="fas fa-bars fa-fw"></i></button>