[英]Cannot use Renderer2 to change attribute of button referenced using ViewChild
I'm currently trying to change an attribute of a button using Renderer2 but I keep getting an error saying: 我目前正在尝试使用Renderer2更改按钮的属性,但我不断收到错误消息:
ERROR TypeError: Cannot read property 'setAttribute' of undefined 错误TypeError:无法读取未定义的属性'setAttribute'
I want to be able to add the disabled attribute to the button when I click it. 我希望能够在单击按钮时将Disabled属性添加到按钮。
I'm using the mat-button component from angular material: https://material.angular.io/components/button/overview 我正在使用角度材料的垫子按钮组件: https : //material.angular.io/components/button/overview
I've tried logging the value of the button reference to the console and it isn't logging 'undefined' 我尝试将按钮引用的值记录到控制台,但未记录“未定义”
Here is the button html element: 这是按钮html元素:
<button #stickButton mat-raised-button color="warn" (click)="onStickButtonClick()">Stick to Bottom</button>
Here is the reference and onclick function inside the typescript class: 这是typescript类中的reference和onclick函数:
constructor(private renderer: Renderer2){
}
@ViewChild('stickButton', {static: false}) private stickButton: ElementRef;
onStickButtonClick(){
this.renderer.setAttribute(this.stickButton.nativeElement, 'disabled', '');
}
The output I'm hoping for is that the button element becomes like this: 我希望得到的输出是button元素变得像这样:
<button #stickButton disabled mat-raised-button color="warn" (click)="onStickButtonClick()">Stick to Bottom</button>
Your code above would work for a normal button, not a button having a material button directive attached. 上面的代码适用于普通按钮,而不适用于附加了材料按钮指令的按钮。
The element you are getting with the ViewChild
is actually of the type MatButton
which doesn't have a property nativeElement. 您通过
ViewChild
获得的元素实际上是MatButton
类型,它没有属性nativeElement。 So what is undefined in your case is 所以在您的情况下未定义的是
this.stickButton.nativeElement
. this.stickButton.nativeElement
。
Since it is a MatButton, you can actually disable the button directly like: 由于它是一个MatButton,因此实际上您可以直接禁用该按钮,例如:
this.stickButton.disabled = true
Here is a complete example: 这是一个完整的示例:
export class AppComponent {
constructor(){
}
@ViewChild('stickButton', {static: false}) private stickButton: MatButton;
onStickButtonClick(){
this.stickButton.disabled = true;
}
}
Here is a stackblitz 这是一次突击
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.