有什么方法可以在 Angular 11 项目的 Typescript 文件中使用 Angular / flex-layout API

San*_*isy 3 typescript angular-material angular-flex-layout angular

Angular Flex Layout 在使用 Angular Material 时非常有用,有没有办法在 TypeScript 文件中使用 flex 布局 API?

例如从这个 URL,有没有办法在 TypeScript 文件中获取 MediaQueries 值?

breakpoint  mediaQuery
xs  'screen and (max-width: 599px)'
sm  'screen and (min-width: 600px) and (max-width: 959px)'
md  'screen and (min-width: 960px) and (max-width: 1279px)'
lg  'screen and (min-width: 1280px) and (max-width: 1919px)'
xl  'screen and (min-width: 1920px) and (max-width: 5000px)'
lt-sm   'screen and (max-width: 599px)'
lt-md   'screen and (max-width: 959px)'
lt-lg   'screen and (max-width: 1279px)'
lt-xl   'screen and (max-width: 1919px)'
gt-xs   'screen and (min-width: 600px)'
gt-sm   'screen and (min-width: 960px)'
gt-md   'screen and (min-width: 1280px)'
gt-lg   'screen and (min-width: 1920px)'
Run Code Online (Sandbox Code Playgroud)

我的意思是在 Angular TypeScript 文件中,我可以使用SMALL,LARGEMEDIUMscreen的媒体查询。

Roy*_*Roy 6

是的,有一种方法可以在 Angular 的 TypeScript 文件中使用这些媒体查询,但它有点隐藏。

您可以使用来自 Angular MaterialBreakpoint Observer API,它为您提供与 Angular 的 FlexLayout API 中使用的媒体查询相同的媒体查询,在 Material Design 中指定

预定义的断点列表(使用的宽度可能不是很明显,但与 Material Design 中的媒体查询一起可以追溯到):

export declare const Breakpoints: {
    XSmall: string;
    Small: string;
    Medium: string;
    Large: string;
    XLarge: string;
    Handset: string;
    Tablet: string;
    Web: string;
    HandsetPortrait: string;
    TabletPortrait: string;
    WebPortrait: string;
    HandsetLandscape: string;
    TabletLandscape: string;
    WebLandscape: string;
};
Run Code Online (Sandbox Code Playgroud)

此列表可以根据您的需要进行扩展。一个简单的例子可以在这里找到作为 StackBlitz

要遵循的步骤:

  1. 导入LayoutModule到您的app.module.ts并将其添加到导入。
import { LayoutModule } from "@angular/cdk/layout";
Run Code Online (Sandbox Code Playgroud)
  1. 导入BreakpointObserver,BreakpointsBreakpointState在您的组件内部。
import {
  BreakpointObserver,
  Breakpoints,
  BreakpointState
} from "@angular/cdk/layout";
Run Code Online (Sandbox Code Playgroud)
  1. 添加BreakpointObserver到构造函数。
  2. 在您的 中ngOnInit,为特定视口(列表)添加观察查询,如断点列表中指定的那样。该列表是一个数组,可以保存多个值:
[Breakpoints.Small, Breakpoints.HandsetPortrait]
Run Code Online (Sandbox Code Playgroud)

代码组合:

export class AppComponent implements OnInit {
  constructor(public breakpointObserver: BreakpointObserver) {}

  viewportWidth: string;

  ngOnInit() {
    this.breakpointObserver
      .observe([Breakpoints.Small, Breakpoints.HandsetPortrait])
      .subscribe((state: BreakpointState) => {
        if (state.matches) {
          this.viewportWidth = "  I am INSIDE the breakpoint";
        } else {
          this.viewportWidth = "  I am OUTSIDE the breakpoint";
        }
      });
  }
}
Run Code Online (Sandbox Code Playgroud)

StackBlitz 上的最终代码。随意发挥您的需求。