3
votes

I'm trying to create a button directive that can receive a boolean via @Input and get bound to the disable attribute of the <button> element.

Here's what I've got so far:

loading-button.directive.ts

@Directive({ selector: '[appLoadingButton]' })
export class LoadingButtonDirective implements OnInit {
  @Input() loaderState: boolean;

  constructor(private renderer: Renderer2, private el: ElementRef) { }

  ngOnInit() {
    this.renderer.setAttribute(this.el.nativeElement, 'disabled', this.loaderState ? 'disabled' : '');
  }
}

template

<button appLoadingButton [loaderState]="submitting"></button>

In that template's component, the submitting property is set to true or false when convenient.

My problem is that this way it is always disabled and I was expecting that the disable attribute was dynamically changing with the directive.

Any help will be greatly appreciated.

1
Well you only set the attribute onInit and since it is not defined as observable, than you never change the state back and forthIgor Dimchevski

1 Answers

11
votes

There are multiple options. One would be to use @HostBinding, and that would be all you need for this:

@Directive({ selector: '[appLoadingButton]' })
export class LoadingButtonDirective {
  @Input() 
  @HostBinding('disabled')
  loaderState: boolean;
}