通过在角度6中创建自定义指令来启用/禁用按钮

时间:2018-11-30 04:16:20

标签: angular html5 angular6 angular2-directives

需要根据条件(即Active = true,然后启用按钮;如果Active = false,然后禁用按钮)在多个HTML页面上动态启用/禁用多个按钮。如何创建和应用自定义指令。

1 个答案:

答案 0 :(得分:-1)

也许是这样的:

.ts

import { NgControl } from '@angular/forms';

@Directive({
  selector: '[disableControl]'
})
export class DisableControlDirective {

  @Input() set disableControl( condition : boolean ) {
    const action = condition ? 'disable' : 'enable';
    this.ngControl.control[action]();
  }

  constructor( private ngControl : NgControl ) {
  }

}

html:

<button [disableControl]="condition">Button 1</button>
<button [disableControl]="condition">Button 2</button>
<button [disableControl]="condition">Button 3</button>

condition将是您组件中的布尔值,必要时将禁用/启用控制。

来源:https://netbasal.com/disabling-form-controls-when-working-with-reactive-forms-in-angular-549dd7b42110