首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何构建禁用所有类型的物料控制的指令?

如何构建禁用所有类型的物料控制的指令?
EN

Stack Overflow用户
提问于 2020-11-20 10:17:37
回答 2查看 218关注 0票数 0

我想要建立一个角指令,当应用于任何控制(物质控制),如matButton/matSelect/matAutcomplete等,应该禁用控制基于条件。有什么帮助吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-11-20 10:35:44

这将是一个过程:

使用角cli创建指令

ng generate directive customMatDisable

这将为您创建一个新的.directive.ts指令文件。

在指令文件中操作元素,如下所示

代码语言:javascript
运行
复制
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>

更新

因为物质指令似乎覆盖了我们的禁用状态,因为它的初始化是在我们的指令执行之后进行的。一个解决办法是这样做:

代码语言:javascript
运行
复制
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
       }
    }
}
票数 1
EN

Stack Overflow用户

发布于 2020-11-20 12:31:23

另一种方法是在构造函数按钮中注入matInput。并使其失效

代码语言:javascript
运行
复制
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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64927632

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档