Button @Directive to bind disable attribute via @Input in Angular

不想你离开。 提交于 2019-12-10 18:55:08

问题


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:


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;
}


来源:https://stackoverflow.com/questions/50798383/button-directive-to-bind-disable-attribute-via-input-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!