【问题标题】:Button @Directive to bind disable attribute via @Input in Angular按钮 @Directive 通过 Angular 中的 @Input 绑定禁用属性
【发布时间】:2018-11-20 17:49:21
【问题描述】:

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

这是我目前得到的:

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 属性在方便时设置为 true 或 false。

我的问题是这样它总是被禁用,我期待禁用属性随着指令动态变化。

任何帮助将不胜感激。

【问题讨论】:

  • 好吧,你只设置属性 onInit 并且因为它没有被定义为可观察的,所以你永远不会来回改变状态

标签: angular directive


【解决方案1】:

有多种选择。一种是使用@HostBinding,这就是你所需要的:

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

【讨论】:

  • @Genís 不客气 :) 99.9% 的时间你真的不需要渲染器
猜你喜欢
  • 2018-07-03
  • 2017-11-29
  • 2018-11-29
  • 1970-01-01
  • 2018-09-29
  • 2017-01-16
  • 1970-01-01
  • 2017-12-03
  • 2015-11-04
相关资源
最近更新 更多