20

How may I add disabled to an input if a condition is met?

What I have today: <input class="previous" [attr.disabled] = "active === 1 ? 'disabled' : ''">

But this adds disabled="disabled" and I want only disabled.

So what I need is: <input class="previous" disabled> if the condition is met.

William
  • 1,010
  • 3
  • 21
  • 39

1 Answers1

59

An attribute can be removed by passing the value null

[attr.disabled] = "active === 1 ? 'disabled' : null">
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Sweet, it still prints `disabled="disabled"` but it solved my problem because when it's false, it will print nothing instead of `disabled=""` – William Jan 16 '17 at 15:47
  • 9
    @William If you want disabled to be reflected in DOM just like `disabled` and not `disabled="disabled"`, pass boolean value to disabled attribute: `[disabled]="active === 1 ? true : false"` – Stefan Svrkota Jan 16 '17 at 15:49
  • 1
    @stefan-svrkota removing the attribute or having the value set to `false` is quite a difference. Also the question was about removing. – Günter Zöchbauer Sep 07 '18 at 06:24
  • 1
    the question is talking about how to disable an input conditionally. while changing the attr appears acceptable. a better solution may be as follows, you can use something like below in the html `` and then in the TS `get shouldBeDisabled():boolean { return {condition here as boolean}; }` – Sam Mar 23 '19 at 11:07