Directive通过Angular中的

Directive通过Angular中的

本文介绍了按钮@Directive通过Angular中的@Input绑定禁用属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个按钮指令,该指令可以通过@Input接收布尔值,并绑定到<button>元素的disable属性.

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' : '');
  }
}

模板

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

在该模板的组件中,方便时将submitting属性设置为truefalse.

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

我的问题是,这种方式总是被禁用,并且我期望disable属性会随着指令而动态更改.

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

任何帮助将不胜感激.

推荐答案

有多个选项.一种方法是使用@HostBinding,这就是您所需要的:

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

这篇关于按钮@Directive通过Angular中的@Input绑定禁用属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 04:17