Search code examples
angulardisabled-input

Need both to disable a checkbox and make it look as it is disabled (style))


I have an HTML element (input of type checkbox), and in my template, I've added the following to the mentioned HTML element:

<input type="checkbox" *ngFor="let status of statuses"
[class.disabled]="status==='Ready' && settings.length > 0 && !settings.includes(status)" [disabled]="status==='Ready' && settings.length > 0 && !settings.includes(status)">

Now, everything works perfectly and exactly the way I want, but I need to duplicate a very long condition:

"status==='Ready' && settings.length > 0 && !settings.includes(status)"

Is there a shorter way to do it?

I can't use only disabled, because then the checkbox would be disabled indeed, but it will look as if it is active and enabled (even though it can't be checked).

I can't use only class.disabled, because then the checkbox would look as disabled, but if I try to check it, I will succeed (it only looks as disabled, but it actually enabled).

Any suggestion, please?


Solution

  • Instead of checking all the condition "status==='Ready' && settings.length > 0 && !settings.includes(status)" in template, use component for this.
    
    you can write a simple function in the component which return either true or false based on the condition
           function disableCheckBox() {
            if(status==='Ready' && settings.length > 0 && !settings.includes(status))
               return true;
            return false;
            }
    and in the template 
        <input type="checkbox" *ngFor="let status of statuses"
        [class.disabled]="disableCheckBox()" [disabled]="disableCheckBox()">
    
    Or Else create a single variable for that