问题在代码中使用Angular Material提供的CDK Overlay模块。
代码示例:
首先,引入Overlay模块:
import { OverlayModule } from '@angular/cdk/overlay';
然后,创建一个主题工厂:
import { ThemePalette } from '@angular/material/core'; import { MatButton } from '@angular/material/button';
@Injectable() export class MyButtonThemeFactory { constructor(private _palette: ThemePalette) {}
createButtonWithTheme(): typeof MatButton { const MyButtonWithTheme = class extends MatButton { constructor(...args: any[]) { super(...args); this.color = this._palette; } };
return MyButtonWithTheme;
} }
然后,在组件中使用CDK Overlay模块创建一个新的按钮:
import { Overlay } from '@angular/cdk/overlay';
@Component({
template:
,
})
export class MyComponent {
@ViewChild('buttonRef') buttonRef: MatButton;
constructor( private _overlay: Overlay, private _buttonThemeFactory: MyButtonThemeFactory, ) {}
ngAfterViewInit() { const MyButtonWithTheme = this._buttonThemeFactory.createButtonWithTheme();
const positionStrategy = this._overlay
.position()
.flexibleConnectedTo(this.buttonRef._elementRef)
.withPositions([
{
originX: 'center',
originY: 'bottom',
overlayX: 'center',
overlayY: 'top',
},
]);
const overlayRef = this._overlay.create({
positionStrategy,
scrollStrategy: this._overlay.scrollStrategies.reposition(),
hasBackdrop: true,
backdropClass: 'cdk-overlay-transparent-backdrop',
panelClass: 'my-panel',
});
overlayRef
.backdropClick()
.subscribe(() => overlayRef.detach());
const buttonPortal = new ComponentPortal(MyButtonWithTheme);
const buttonRef = overlayRef.attach(buttonPortal);
} }
这样就可以在Angular Material v15里更新工程中遗留的按钮样式,保证所设置的主题可以应用于所有按钮。