无法使用Renderer2在Angular Material Select上设置disabled属性

3

我无法使用renderer2禁用Angular Material的下拉选择框。以下是我的代码:

Component.html

            <mat-select #exLoc (selectionChange)="someFun($event)" [(value)]="someVal">
              <mat-option aria-selected="true" [value]="locVal" *ngFor="let location of locations">{{location.LocationName}}
              </mat-option>
            </mat-select>

Component.ts

constructor(public renderer: Renderer2) {} 
@ViewChild('exLoc') exLoc: ElementRef;
functionToDisableDropDown() {
 this.renderer.setAttribute(this.exLoc, 'disabled', 'true');
}

在哪里以及如何调用functionToDisableDropDown()函数? - undefined
1
<mat-select [disabled]='isDropDownDisabled' ...> functionToDisableDropDown() { this.isDropDownDisabled = true;} - undefined
@Vega:在某个其他按钮的点击事件上调用该函数。该方法被调用了。我用console.log进行了检查。 - undefined
@RaviYadav 请给我的评论点赞 - undefined
@RaviYadav 我已经更新了我的答案。请检查一下。使用 MatSelect 替代 ElementRef - undefined
显示剩余3条评论
4个回答

6

正确的方法是使用Renderer2。

disabled是一个属性,所以它不能与您的代码一起工作。

正确的代码:

this.renderer.setProperty(this.exLoc, 'disabled', true);
this.renderer.setProperty(this.exLoc, 'disabled', false);

1

exLoc的类型从ElementRef更改为MatSelect

constructor(public renderer: Renderer2) {} 
@ViewChild('exLoc') exLoc: MatSelect;

functionToDisableDropDown() {
  // not sure why is this not working
  //this.renderer.setAttribute(this.exLoc, 'disabled', 'true');

  // without using renderer
  this.exLoc.disabled = true;
}

正在工作中 演示


试过了,没有成功。最终我在HTML中添加了[disabled] = "value",并在.ts文件中将其设置为true和false,而不是调用renderer2方法来获取所需的结果。但我仍然不明白为什么上述代码不起作用。 - undefined
不使用渲染器(renderer),它是否正常工作,例如this.exLoc.nativeElement.disabled = true; - undefined
是的,正如我所说,我得到了期望的结果。但我的问题是为什么它与renderer2不起作用。 - undefined
这可能是Renderer2的一个bug,它不接受MatSelect作为输入。 - undefined

0
使用 -> this.render.setProperty(this.exLoc.nativeElement, 'disabled', true); ".nativeElement

请解释你的答案,并使用反引号格式化代码,以便更容易理解和阅读。 - undefined
你好,欢迎来到SO!请编辑帖子并将代码格式化在你的回答中。这样可以使你的回答更加合理,并清楚地展示你想要解释的内容。 - undefined

0

我知道这是一个老问题,但真正的问题可能在于MatSelect是一个自定义元素,它实际上没有disabled属性。MatSelect可能有自己的ControlValueAccessor管理方式。所以如果你想禁用一个MatSelect元素,你应该有一个对该组件的引用,并使用它自己的setDisabledState方法(从ControlValueAccessor接口实现)。

setDisabledState(isDisabled: boolean): void

例如:

 @ViewChild(MatSelect)
 private _myMatSelect: MatSelect;

 ...

 xxx() {
     this._myMatSelect.setDisabledState(true); // Should trigger the engine to disable your MatSelect element.
 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接