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

时间:2018-07-05 08:40:13

标签: javascript html angular css-selectors angular-services

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

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>

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

谢谢

4 个答案:

答案 0 :(得分:1)

您可以尝试使用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>

答案 1 :(得分:1)

使用以下代码更新代码:

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

答案 2 :(得分:1)

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

答案 3 :(得分:0)

您需要在JavaScript中使用Array.length

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