【问题标题】:How to disable Mat Radio button in Angular?如何在 Angular 中禁用 Mat Radio 按钮?
【发布时间】:2021-08-23 21:16:26
【问题描述】:

如果我在 html 中使用 disabled= true 属性,则 mat 单选按钮将正确禁用,但如果我必须通过某些功能禁用某些单选按钮,我将通过渲染器设置禁用属性,例如

this.renderer.setAttribute(this.matRadio.nativeElement, 'disabled', 'true');

不会禁用单选按钮。我应该如何通过函数禁用某些单选按钮?

【问题讨论】:

  • 你使用什么 changeDetection 策略?
  • 默认一个...我没有更改任何更改检测策略

标签: javascript angular


【解决方案1】:

这应该可以工作。因为您正在使用 Renderer 更新禁用 css 类可能不会被添加。

除了上述功能,您还需要添加禁用类

this.renderer.setAttribute(this.matRadio.nativeElement, 'disabled', 'true');
this.renderer.addClass(this.matRadio.nativeElement, 'mat-radio-disabled')

请试试这个

【讨论】:

  • 它正在应用禁用的类和样式,但单选按钮实际上并未禁用,我仍然可以单击它
  • 使用this.matRadio 变量您在html 中使用@ViewChild 指的是哪一个?可以展示一下吗?
  • <mat-radio-button #matRadio></mat-radio-button> ...我实际上是在使用 viewChildren 来获取所有具有#matRadio 参考的垫子单选按钮。然后使用this.renderer.setAttribute(this.matRadio.toArray()[index].nativeElement, 'disabled', 'true') 并设置类
  • 为什么不能用@ViewChildren('matRadio') matRadio: QueryList<MatRadioButton>;,可以用this.matRadio.toArray().forEach( radio => radio.disabled = true);.
  • 你在哪里写this.matRadio.toArray().forEach( radio => radio.disabled = true)是在ngOnInit()里面吗?
【解决方案2】:

先获取元素,再使用element.setAttribute("disabled","true")

【讨论】:

    【解决方案3】:

    您可以使用响应式表单:

    在创建 FormControl 时禁用:

    formControl = new FormControl({ value: '', disabled: true }),
    

    以编程方式禁用:

    this.formControl.disable();
    

    【讨论】:

    • 不使用表单控制...只是简单的单选按钮
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-29
    • 2018-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-22
    • 1970-01-01
    相关资源
    最近更新 更多