如何获取Angular Material按钮尺寸?(版本>7.2)
获取Angular Material按钮尺寸的替代方案
在Angular Material版本>7.2.2时,原全局CSS自定义属性--mdc-icon-button-state-layer-size已被移除,无法直接通过该属性获取按钮尺寸,以下是几种可行的替代方法:
直接读取DOM元素的渲染尺寸
通过ViewChild获取按钮的DOM元素引用,直接读取其offsetWidth和offsetHeight属性,这是最直接的方法,能拿到按钮实际渲染后的尺寸:import { Component, ElementRef, ViewChild, AfterViewInit } from '@angular/core'; @Component({ selector: 'app-example', template: '<button #iconBtn mat-icon-button><mat-icon>menu</mat-icon></button>' }) export class ExampleComponent implements AfterViewInit { @ViewChild('iconBtn') iconBtn!: ElementRef<HTMLButtonElement>; ngAfterViewInit() { const width = this.iconBtn.nativeElement.offsetWidth; const height = this.iconBtn.nativeElement.offsetHeight; console.log(`按钮尺寸:${width}px × ${height}px`); } }通过预设类推断尺寸
Angular Material的图标按钮提供了预设尺寸类(mat-small-button、默认、mat-large-button),对应Material Design规范的固定尺寸:- 小型按钮:32px × 32px
- 默认按钮:40px × 40px
- 大型按钮:48px × 48px
可以通过检查元素的类名来推断尺寸:
import { Component, ElementRef, ViewChild } from '@angular/core'; @Component({ selector: 'app-example', template: '<button #iconBtn mat-icon-button mat-large-button><mat-icon>menu</mat-icon></button>' }) export class ExampleComponent { @ViewChild('iconBtn') iconBtn!: ElementRef<HTMLButtonElement>; getButtonSize() { const btnElement = this.iconBtn.nativeElement; let size = { width: 40, height: 40 }; if (btnElement.classList.contains('mat-small-button')) { size = { width: 32, height: 32 }; } else if (btnElement.classList.contains('mat-large-button')) { size = { width: 48, height: 48 }; } return size; } }监听尺寸变化(响应式场景)
如果按钮尺寸会随窗口大小或布局变化,可结合Angular CDK的BreakpointObserver监听断点变化,同时重新获取尺寸:import { Component, ElementRef, ViewChild, AfterViewInit } from '@angular/core'; import { BreakpointObserver } from '@angular/cdk/layout'; @Component({ selector: 'app-example', template: '<button #iconBtn mat-icon-button><mat-icon>menu</mat-icon></button>' }) export class ExampleComponent implements AfterViewInit { @ViewChild('iconBtn') iconBtn!: ElementRef<HTMLButtonElement>; constructor(private breakpointObserver: BreakpointObserver) {} ngAfterViewInit() { this.breakpointObserver.observe(['(max-width: 768px)', '(min-width: 769px)']) .subscribe(() => { const width = this.iconBtn.nativeElement.offsetWidth; const height = this.iconBtn.nativeElement.offsetHeight; console.log('更新后的按钮尺寸:', width, height); }); } }
内容的提问来源于stack exchange,提问作者Kasimier Buchcik
相关产品推荐
相关产品推荐

