首页 > 解决方案 > 如何在 Angular 中获取 Angular Material 元素的值?

问题描述

我有这个 HTML 小代码,一个是普通的 HTML 按钮,另一个是 Angular Material Icon 按钮。

<button mat-button #matbutton value="007">mat-button</button>

<button #button value="342">button</button>

我试图在 .ts 文件中获取它们的值,如下所示:

  @ViewChild('matinput', { static: true }) matinput: ElementRef;
  @ViewChild('button', { static: true }) button: ElementRef;

  ngAfterViewInit(){
    console.log(this.button.nativeElement.value);  
    console.log(this.matinput.nativeElement.value);
  }

我只获取普通HTML按钮的值,却获取不到角材质按钮的值……怎么实现呢?我尝试删除“nativeElement”,但也没有用。

谢谢

标签: angularangular-material

解决方案


您正在使用该mat-button指令,因此如果您想获取此按钮(MatButton)的 elementRef,您需要显式read: ElementRef声明ViewChild.

默认ViewChild是读取元素作为指令。

@ViewChild('matButton', { static: true, read: ElementRef }) matButton: ElementRef;

关于 ViewChild 的资源:

https://angular.io/api/core/ViewChild

https://blog.angular-university.io/angular-viewchild/


推荐阅读