-1

Am trying to disable a button if an array isemty but fails

<button [disabled]="(users.length ==0 )?true:false">Send mass emails</button>

IN the ts file

users: UsersModel[];

THe above throws an error

Bindings cannot contain assignments at column

How do i disable that button if the array is emty

Liam
  • 27,717
  • 28
  • 128
  • 190
Geoff
  • 6,277
  • 23
  • 87
  • 197
  • Not sure about angular2, but I guess angular1 had `ng-enable`. angular2 also must have something similar. Also just a POV, but its always better to use functions instead of inline expression. This way, you will keep your view clean and code more modular – Rajesh Jul 05 '17 at 15:45

2 Answers2

4

It doesn't look like you initialized the users: UsersModel[] array in your component so it's coming back as undefined and you are trying to access length property of an undefined object/array. Try the following to disable the button if users array has NOT been initialized or the length is equal to 0:

<button type="button" [disabled]="!users || users.length === 0">Send Mass Emails</button>

Here is plunkr demonstrating this in action.

What you could also consider is initializing the user array to an empty array in your component:

users: UsersModel[] = [];

Then you could simply do to disable/enable the button based on users length being zero/falsy:

<button type="button" [disabled]="!user.length">Send mass emails</button>

Here is a plunkr demonstrating initializing the users array to an empty array and checking length to disable button accordingly.

Hopefully that helps!

Alexander Staroselsky
  • 37,209
  • 15
  • 79
  • 91
0
<button [disabled]="users.length===0?true:false">Send mass emails</button>

You can add you condition to the disabled tag like the following. even you can check for the users array then check the length like

<button [disabled]="!user || users.length===0?true:false">Send mass emails</button>
Rahul Singh
  • 19,030
  • 11
  • 64
  • 86
  • 1
    Missing explanation. -1. Answers without explanation are incomplete. Please post answers explaining **What and Why** your solution solves – Rajesh Jul 05 '17 at 15:48
  • @Rajesh its was pretty self explanatory – Rahul Singh Jul 05 '17 at 15:50
  • 2
    To you and me, yes. But SO is a place for everyone. You are answering for readers and you cannot be sure of readers' level. Hence explanation. – Rajesh Jul 05 '17 at 15:51