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.

0

1 Answer 1

59

An attribute can be removed by passing the value null

[attr.disabled] = "active === 1 ? 'disabled' : null">
Sign up to request clarification or add additional context in comments.

4 Comments

Sweet, it still prints disabled="disabled" but it solved my problem because when it's false, it will print nothing instead of disabled=""
@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 removing the attribute or having the value set to false is quite a difference. Also the question was about removing.
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 <input [disabled]="shouldBeDisabled"> and then in the TS get shouldBeDisabled():boolean { return {condition here as boolean}; }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.