如何通过打字稿中的指令阻止垫选择?

如何解决如何通过打字稿中的指令阻止垫选择?

我正在使用Angular 9 /打字稿。我想在某些条件下禁用某些表单元素。我发现了这样一个good example,作者禁用了所有元素。我编辑了他的例子。一切都很好,但是MAT-SELECT未被禁用,并且仍然是唯一的活动元素。请告诉我如何禁用它?

enter image description here

文章示例:

private disableElement(element: any) {
    if (this.appDisable) {
      if (!element.hasAttribute(DISABLED)) {
        this.renderer.setAttribute(element,APP_DISABLED,'');
        this.renderer.setAttribute(element,DISABLED,'true');

        // disabling anchor tab keyboard event
        if (element.tagName.toLowerCase() === TAG_ANCHOR) {
          this.renderer.setAttribute(element,TAB_INDEX,'-1');
        }
      }
    } else {
      if (element.hasAttribute(APP_DISABLED)) {
        if (element.getAttribute('disabled') !== '') {
          element.removeAttribute(DISABLED);
        }
        element.removeAttribute(APP_DISABLED);
        if (element.tagName.toLowerCase() === TAG_ANCHOR) {
          element.removeAttribute(TAB_INDEX);
        }
      }
    }
    if (element.children) {
      for (let ele of element.children) {
        this.disableElement(ele);
      }
    }
  }

我的代码:

private disableElement(element: any) {
    if (this.appDisable) {
      if (element.tagName == "INPUT" || element.tagName == "MAT-SELECT" || element.tagName == "BUTTON") {
        if (!element.hasAttribute(DISABLED)) {
          this.renderer.setAttribute(element,'');
          this.renderer.setAttribute(element,'true');

          // disabling anchor tab keyboard event
          if (element.tagName.toLowerCase() === TAG_ANCHOR) {
            this.renderer.setAttribute(element,'-1');
          }
        }
      }
    } else {
      if (element.tagName == "INPUT" || element.tagName == "MAT-SELECT" || element.tagName == "BUTTON") {
        if (element.hasAttribute(APP_DISABLED)) {
          if (element.getAttribute('disabled') !== '') {
            element.removeAttribute(DISABLED);
          }
          element.removeAttribute(APP_DISABLED);
          if (element.tagName.toLowerCase() === TAG_ANCHOR) {
            element.removeAttribute(TAB_INDEX);
          }
        }
      }
    }
    if (element.children) {
      for (let ele of element.children) {
        this.disableElement(ele);
      }
    }
  }

解决方法

您上面的代码适用于常规选择,而不适用于附加了材料指令的垫选。

与ViewChild一起获得的元素实际上是MatSelect类型,它没有属性nativeElement。因此,根据您的情况未定义的是。

但是您不能只使用以下内容吗??

在您的模板中

  <mat-select [disabled]=isDisabled >
    <mat-option *ngFor="let topping of toppingList" [value]="topping">{{topping}}</mat-option>
  </mat-select>

,并且在您的组件中,可以在特定条件下将“ isDisabled”设置为true或false。

,

问题在于,垫子选择不是输入选择

如果您正在使用ReactiveForms,则可以创建自己的指令。使用FormControl的enable()disable()方法的人

类似的指令

import {Directive,Input,} from "@angular/core";
import { FormGroupDirective } from "@angular/forms";

@Directive({
  selector: "[appDisable]"
})
export class DisableDirective {
  constructor(private fgd: FormGroupDirective) {}
  @Input() set appDisable(value: boolean) {
    Object.keys(this.fgd.form.controls).forEach(x => {
      const control = this.fgd.form.get(x);
      if (control) {
        if (value) control.disable();
        else control.enable();
      }
    });
  }
}

您可以使用表格

<form [formGroup]="form" [appDisable]="disabled">
    <mat-form-field appearance="fill">
        <mat-label>Favorite food</mat-label>
        <mat-select formControlName="food">
            <mat-option *ngFor="let food of foods" [value]="food.value">
                {{food.viewValue}}
            </mat-option>
        </mat-select>
    </mat-form-field>
    <mat-form-field appearance="fill">
        <mat-label>Name</mat-label>
        <input matInput formControlName="name"/>
    </mat-form-field>
</form>
<button mat-button (click)="disabled=!disabled">{{disabled?'Enable!':'Disable!'}}</button>

请参阅stackblitz

更新如何到达按钮或如何到达NgControls 如果需要到达按钮或NgControl,则需要使用ContentChild和ContenChildren。我们可以声明两个变量

  @ContentChild(MatButton) button: MatButton;
  @ContentChildren(NgControl,{ descendants: true }) controls: QueryList<NgControl>;

要获取ContentChild,我们只能在ngAfterView初始化之后才能到达,将setter中的代码转换为函数。好吧,我们更改了功能,所以,因为我们不使用反应式窗体,我们也禁用了控件。

  setEnabled(value: boolean) {
    if (this.fgd) { //we are using with a [formGroup]
      Object.keys(this.fgd.form.controls).forEach(x => {
        const control = this.fgd.form.get(x);
        if (control) {
          if (value) control.disable();
          else control.enable();
        }
      });
    } else { //we are not using Reactive Forms
      if (this.controls) {
        this.controls.forEach(x => {
          const control = x.ngControl;
          if (control) {
            if (value) control.disable();
            else control.enable();
          }
        });
      }
    }
    //to disabled/enabled the submitButton
    if (this.button) this.button.disabled = value;
  }

好吧,我们需要在ngAfterViewInit和setter中调用该函数,并使用新的私有变量_disable

  @Input() set appDisable(value: boolean) {
    this._disable = value;
    this.setEnabled(value);
  }
  ngAfterViewInit() {
      this.setEnabled(this._disable);
  }

注意:我们对所有这些更改进行了堆栈闪电更新

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-