如何使用 Angular CDK 检测断点

简介

ANGLING CDK有一个布局包,其中包含检测视区大小和匹配媒体查询的服务。这允许您完全控制用户界面,并适应不同的屏幕大小。

在本文中,您将在ANGLE项目中应用CDK的布局模块。

前提条件

如果您想继续阅读本文,您将需要:

本教程已经在Node v16.6.1、npm7.20.3、@angular/corev12.2.0和@angular/cdkv12.2.0上进行了验证。

设置项目

您可以使用@ANGLE/CLI创建一个新的角度投影。

在您的终端窗口中,使用以下命令:

1ng new AngularBreakpointsExample --style=css --routing=false --skip-tests

这将配置一个新的角度项目,将样式设置为),不布线,并跳过测试。

导航到新创建的项目目录:

1cd AngularBreakpointsExample

接下来,安装@angular/cdk

1npm install @angular/[email protected]

然后导入布局模块,并将其添加到NgModule的导入列表中:

 1[label src/app/app.module.ts]
 2import { NgModule } from '@angular/core';
 3import { BrowserModule } from '@angular/platform-browser';
 4import { LayoutModule } from '@angular/cdk/layout';
 5
 6import { AppComponent } from './app.component';
 7
 8@NgModule({
 9  declarations: [
10    AppComponent
11  ],
12  imports: [
13    BrowserModule,
14    LayoutModule
15  ],
16  providers: [],
17  bootstrap: [AppComponent]
18})
19export class AppModule { }

现在,您可以开始使用组件中的可用服务和实用程序了。让我们逐一讨论一下。

使用Breakpoint tObserver.serveBreakpoint tState

serve方法返回一个Breakpoint tState类型的可观测对象,可以用来观察视区在匹配或不匹配媒体查询之间发生变化。

下面是一个例子,如果视口大小在小于500px和等于或大于500px之间变化,则会将消息记录到控制台:

 1[label src/app/app.component.ts]
 2import { Component, OnInit } from '@angular/core';
 3import {
 4  BreakpointObserver,
 5  BreakpointState
 6} from '@angular/cdk/layout';
 7
 8@Component({ 
 9  selector: 'app-root',
10  templateUrl: './app.component.html',
11  styleUrls: ['./app.component.css']
12})
13export class AppComponent implements OnInit {
14  constructor(public breakpointObserver: BreakpointObserver) {}
15
16  ngOnInit() {
17    this.breakpointObserver
18      .observe(['(min-width: 500px)'])
19      .subscribe((state: BreakpointState) => {
20        if (state.matches) {
21          console.log('Viewport width is 500px or greater!');
22        } else {
23          console.log('Viewport width is less than 500px!');
24        }
25      });
26  }
27}

<$>[备注] 注意: 您可能还需要将{title}}app.Component.html中移除以防止出错。 <$>

Breakpoint tState接口为我们提供了一个名为matches的布尔属性。

使用断点

除了使用手工编写的媒体查询,我们还可以使用BreakPoints对象,它为我们提供了常见断点的键:

 1[label src/app/app.component.ts]
 2import { Component, OnInit } from '@angular/core';
 3import {
 4  BreakpointObserver,
 5  Breakpoints,
 6  BreakpointState
 7} from '@angular/cdk/layout';
 8
 9@Component({ 
10  selector: 'app-root',
11  templateUrl: './app.component.html',
12  styleUrls: ['./app.component.css']
13})
14export class AppComponent implements OnInit {
15  constructor(public breakpointObserver: BreakpointObserver) {}
16
17  ngOnInit() {
18    this.breakpointObserver
19      .observe([Breakpoints.Small, Breakpoints.HandsetPortrait])
20      .subscribe((state: BreakpointState) => {
21        if (state.matches) {
22          console.log(
23            'Matches small viewport or handset in portrait mode'
24          );
25        }
26      });
27  }
28}

本例使用Breakpoints.SmallBreakpoints.HandsetPortrait的预定义断点。

使用Breakpoint tObserver.isMatched

对于一次性匹配,我们可以使用isMatching方法

 1[label src/app/app.component.ts]
 2import { Component, OnInit } from '@angular/core';
 3import {
 4  BreakpointObserver,
 5  BreakpointState
 6} from '@angular/cdk/layout';
 7
 8@Component({ 
 9  selector: 'app-root',
10  templateUrl: './app.component.html',
11  styleUrls: ['./app.component.css']
12})
13export class AppComponent implements OnInit {
14  constructor(public breakpointObserver: BreakpointObserver) {}
15
16  ngOnInit() {
17    if (this.breakpointObserver.isMatched('(min-height: 40rem)')) {
18      console.log('Viewport has a minimum height of 40rem!');
19    }
20  }
21}

如果组件初始化时,视区高度至少为40 rem,则会记录一条消息。

使用MediaMatcher

MediaMatcher是一个包装了JavaScript的matchMedia的服务。与Breakpoint tObserver.serve一样,它也可以用来观察针对给定媒体查询的视区大小的变化。

下面是一个检查min-width是否为500 px wide的示例:

 1[label src/app/app.component.html]
 2import { Component, OnInit, OnDestroy } from '@angular/core';
 3import { MediaMatcher } from '@angular/cdk/layout';
 4
 5@Component({ 
 6  selector: 'app-root',
 7  templateUrl: './app.component.html',
 8  styleUrls: ['./app.component.css']
 9})
10export class AppComponent implements OnInit, OnDestroy {
11  matcher!: MediaQueryList;
12
13  constructor(public mediaMatcher: MediaMatcher) {}
14
15  ngOnInit() {
16    this.matcher = this.mediaMatcher.matchMedia('(min-width: 500px)');
17
18    this.matcher.addEventListener('change', this.myListener);
19  }
20
21  ngOnDestroy() {
22    this.matcher.removeEventListener('change', this.myListener);
23  }
24
25  myListener(event: { matches: any; }) {
26    console.log(event.matches ? 'match' : 'no match');
27  }
28}

Breakpoint tObserver.serve的不同之处在于,MediaMatcher让我们可以访问在某些场景下可能需要的原生MatchQueryListobject,。

<$>[备注] 注意: 本示例之前使用的是addListeneremoveListeneraddListener已弃用,现代浏览器推荐使用addEventListenerremoveListener已弃用,现代浏览器推荐使用emoveEventListener。 <$>

现在,您已经拥有了做出反应或调整您的UI以适应不同角度的视区大小所需的一切。

结论

在本文中,将CDK的布局模块应用于角度项目。

继续学习CDK布局模块接口reference.的文档

Published At
Categories with 技术
Tagged with
comments powered by Disqus