繁体   English   中英

无法使用Renderer2更改使用ViewChild引用的按钮的属性

[英]Cannot use Renderer2 to change attribute of button referenced using ViewChild

我目前正在尝试使用Renderer2更改按钮的属性,但我不断收到错误消息:

错误TypeError:无法读取未定义的属性'setAttribute'

我希望能够在单击按钮时将Disabled属性添加到按钮。

我正在使用角度材料的垫子按钮组件: https : //material.angular.io/components/button/overview

我尝试将按钮引用的值记录到控制台,但未记录“未定义”

这是按钮html元素:

<button #stickButton mat-raised-button color="warn" (click)="onStickButtonClick()">Stick to Bottom</button>

这是typescript类中的reference和onclick函数:

constructor(private renderer: Renderer2){
}

@ViewChild('stickButton', {static: false}) private stickButton: ElementRef;

onStickButtonClick(){
  this.renderer.setAttribute(this.stickButton.nativeElement, 'disabled', '');
}

我希望得到的输出是button元素变得像这样:

<button #stickButton disabled mat-raised-button color="warn" (click)="onStickButtonClick()">Stick to Bottom</button>

上面的代码适用于普通按钮,而不适用于附加了材料按钮指令的按钮。

您通过ViewChild获得的元素实际上是MatButton类型,它没有属性nativeElement。 所以在您的情况下未定义的是

this.stickButton.nativeElement

由于它是一个MatButton,因此实际上您可以直接禁用该按钮,例如:

this.stickButton.disabled = true

这是一个完整的示例:

export class AppComponent  {
  constructor(){
  }

  @ViewChild('stickButton', {static: false}) private stickButton: MatButton;

  onStickButtonClick(){
    this.stickButton.disabled = true;
  }
}

这是一次突击

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM