我想要建立一个角指令,当应用于任何控制(物质控制),如matButton/matSelect/matAutcomplete等,应该禁用控制基于条件。有什么帮助吗?
发布于 2020-11-20 10:35:44
这将是一个过程:
使用角cli创建指令
ng generate directive customMatDisable
这将为您创建一个新的.directive.ts指令文件。
在指令文件中操作元素,如下所示
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[customMatDisable]'
})
export class CustomMatDisableDirective {
constructor(el: ElementRef) {
if(//condition here){
el.nativeElement.disabled = true;
}
}
}并使用如下所示:<button customMatDisable mat-raised-button >Button Text</button>
更新
因为物质指令似乎覆盖了我们的禁用状态,因为它的初始化是在我们的指令执行之后进行的。一个解决办法是这样做:
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[customMatDisable]'
})
export class CustomMatDisableDirective {
constructor(el: ElementRef) {
if(//condition here){
setTimeout(()=>{
el.nativeElement.disabled = true;
el.nativeElement.classList.add("mat-button-disabled")
},1) //execute after 1 ms
}
}
}发布于 2020-11-20 12:31:23
另一种方法是在构造函数按钮中注入matInput。并使其失效
export class CustomMatDisableDirective implements OnInit {
constructor(
@Optional() @Self() private control:NgControl,
@Optional() @Self() private button:MatButton,
@Optional() @Self() private input:MatInput,
@Optional() @Self() private select:MatSelect,
@Optional() @Self() private toogle:MatDatepickerToggle<any>,
) {}
ngOnInit() {
if (this.control && this.control.control)
this.control.control.disable()
if (this.button)
this.button.disabled=true
if (this.input)
this.input.disabled=true;
if (this.select)
this.select.disabled=true;
if (this.toogle)
this.toogle.disabled=true;
}请参阅stackblitz
https://stackoverflow.com/questions/64927632
复制相似问题