0

I have this button:

<button class="btn btn-primary btn-sm" (click)="addSupplier(item)">Save</button>

I would like to add a class 'disabled' that will only applied when a certain condition is true, and will not apply when it is false.

What is the Angular 2 way of doing this? I came up with this approach using *ngIf but it's a ton of code:

<div *ngIf="item.productId && item.supplier">
    <button class="btn btn-primary btn-sm" (click)="addSupplier(item)">Save</button>
</div>
<div *ngIf="!item.productId || !item.supplier">
    <button class="btn btn-primary btn-sm disabled" (click)="addSupplier(item)">Save</button>
</div>
4
  • Possible duplicate of Assign classes conditionally in Angular2 Commented Mar 21, 2017 at 21:58
  • The answer provided here is different than the one at the link and I like it better. But the question is a duplicate. Commented Mar 21, 2017 at 21:59
  • I agree that is correctly marked as duplicate. But why are the answers irrelevant if they are different or better? Commented Mar 21, 2017 at 22:11
  • Again, there is no argument that this question is a duplicate and has been properly marked as such. But will users be able to continue to answer this question? As we have seen the answer that @Robin has provided here is better than the answer in the duplicate. This would actually suggest that asking a duplicate question can be a good thing for everyone. Commented Mar 21, 2017 at 22:22

3 Answers 3

2
<button class="btn btn-primary btn-sm" [class.disabled]="!item.productId || !item.supplier" (click)="addSupplier(item)">Save</button>
Sign up to request clarification or add additional context in comments.

Comments

2

The good old ngClass is still available in Angular 2. You can give a try if you want.

[ngClass]="{'my-class': isClassVisible }"

Comments

0

If you are simply trying to disable the button you may not need a css class, bind to [disabled] like [disabled]="disableButton"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.