3

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
  • 1
    Well you only set the attribute onInit and since it is not defined as observable, than you never change the state back and forth Commented Jun 11, 2018 at 13:09

1 Answer 1

13

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

@Genís you're welcome :) 99.9% of the time you really don't need the renderer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.