angular - 如何在 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”,但也没有用。
谢谢
解决方案
您正在使用该mat-button
指令,因此如果您想获取此按钮(MatButton)的 elementRef,您需要显式read: ElementRef
声明ViewChild
.
默认ViewChild
是读取元素作为指令。
@ViewChild('matButton', { static: true, read: ElementRef }) matButton: ElementRef;
关于 ViewChild 的资源:
推荐阅读
- python - 在 python 3 中覆盖 __hex__?
- jupyter-notebook - 使用 folium 在地图上绘制聚类点时出现错误“列表索引必须是整数或切片,而不是浮点数”
- java - Java BigInteger 与 C# 的差异结果
- flutter - 无法合并 Firestore 流
- ios - 如何在 Swift 5 中的 UIScrollView 内以编程方式生成的 UIView 上实现 Tap Gesture
- html - 只显示用户自己 Laravel 的通知
- flutter - Flutter 中 factory 关键字的作用是什么?
- ios - Swift - 如何搜索结构数组
- sql - 为什么 INTEGER/INTEGER 没有在 SQL 中给我答案?
- c - MPI - 异步环通信