之前我使用 mediaObserver.media$ 检测屏幕大小,然后使用该信息使用 *ngIf 添加或删除 DOM 元素。示例代码如下。但是, media$ 不再可用。现在有人知道如何使用 mediaObserver 吗?
应用组件
export class AppComponent implements OnInit, OnDestroy {
mediaSub: Subscription;
deviceXs: boolean;
constructor(public mediaObserver: MediaObserver) {}
ngOnInit() {
this.mediaSub = this.mediaObserver.media$.subscribe((res: MediaChange) => {
console.log(res.mqAlias);
this.deviceXs = res.mqAlias === "xs" ? true : false;
})
}
ngOnDestroy() {
this.mediaSub.unsubscribe();
}
}
通过将 deviceXs 注入任何 component.ts 的上述代码,我可以使用 component.html 中的 *ngIf 来控制 DOM 元素,如下所示。
Header component.ts
export class HeaderComponent {
@Input() deviceXs: boolean;
}
Header component.html
<button *ngIf="deviceXs" mat-icon-button [matMenuTriggerFor]="menu">
我现在如何在没有 mediaObserver.media$ 的情况下实现这一目标?n