Alexis Le Gal Alexis Le Gal - 3 months ago 5
TypeScript Question

Directive need to be refreshed when input change

I made the following directive :

import { Directive, ElementRef, HostListener, Input, OnInit } from '@angular/core';
import { Observable, Subscription } from 'rxjs/Rx';

@Directive({
selector: '[myDisabled]'
})

export class DisableDirective implements OnInit {
private el: HTMLElement;

@Input('myDisabled') isDisable: boolean;

constructor(el: ElementRef) { this.el = el.nativeElement;}

ngOnInit() {
this.disable();
}

private disable() {
this.isDisable ? this.el.style.opacity = '0.65' : this.el.style.opacity = '1';
}
}


This directive set the opacity of a button depend on an input : isDesable. This setting need to be refreshed when the input change, however, I don't know how to do it.

I use this directive like this :

<button class="btn" [myDisabled]="!sharedDetails.isEnabled">A button !</button>

Answer

Two ways

_isDisabled: boolean;
@Input('myDisabled') 
set isDisable(value: boolean)  {
  this._isDisabled = value;
  this.disable();
}

or

// called every time after inputs are updated
// check the `changes` parameter for details if you have more than one input
ngOnChanges(changes) {
  this.disable();    
}
Comments