'How to remove angular expression attributes from element

I'd like to know whether it's possible to remove Angular expressions dynamically. I tried the following without any success:

My button

<button myDirective [disabled]="someExpression">Clippy</button>

My Directive

@Directive({
   selector: '[myDirective]'
})
export class MyDirective {
   constructor(private element: ElementRef) {}

   ngOnInit() {
      this.element.nativeElement.removeAttribute('disabled');
   }
}

The problem

Initially the button won't be disabled, but once someExpression re-evaluates it'll add the disabled attribute back to the element.

Just for clarification, I want to remove an Angular expression dynamically. In the above example it's [disabled]. But this can be any binding in the future. I want my directive to overrule the existing binding.



Solution 1:[1]

Use @HostBinding, e.g.

import { Directive, HostBinding } from '@angular/core';

@Directive({
  selector: '[statusDirective]',
})
export class StatusDirective {
  @HostBinding('disabled') disable = true;
  constructor() {}
}

//Your input never enabled
//<input type="text" name="id" [disabled]="false" statusDirective  >

Solution 2:[2]

<button myDirective [disabled]="hideAttr">Clippy - {{hideAttr}}</button>

the disabled attribute is not removed when hideAttr is false

https://plnkr.co/edit/h86IUsny6MiLfRI9tsPx

Solution 3:[3]

You probably need two copies of the button but only one of them displayed at a time

<ng-container *ngIf="showButtonWithDisabledExpr">
        <button [disabled]="someExpression">Clippy</button>
</ng-container>

<ng-container *ngIf="!showButtonWithDisabledExpr">
        <button>Clippy</button>
</ng-container>

Solution 4:[4]

In newer Angular versions you need to make sure the expression evaluates to null or undefined:

When the expression resolves to null or undefined, Angular removes the attribute altogether.

See Attribute Binding.

So an example would be:

<button [disabled]="someExpression ? '' : null">Clippy</button>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eliseo
Solution 2
Solution 3 kodebot
Solution 4 dastrobu