-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

1
  • 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 Commented Jul 5, 2017 at 15:45

2 Answers 2

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!

Sign up to request clarification or add additional context in comments.

Comments

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>

3 Comments

Missing explanation. -1. Answers without explanation are incomplete. Please post answers explaining What and Why your solution solves
@Rajesh its was pretty self explanatory
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.