问题
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