如何使用AngularCDK检测断点
介绍
Angular CDK 有一个布局包,其中包含检测视口大小和匹配媒体查询的服务。 这使您可以完全控制 UI 并适应不同的屏幕尺寸。
在本文中,您将在 Angular 项目中应用 CDK 的布局模块。
先决条件
如果您想继续阅读本文,您将需要:
- Node.js 安装在本地,您可以按照【X57X】如何安装Node.js 并创建本地开发环境【X126X】进行。
- 本教程还将假设您已全局安装 @angular/cli。
- 对 CSS 媒体查询 有一定的了解。
本教程已使用 Node v16.6.1、npm 7.20.3、@angular/core v12.2.0 和 @angular/cdk v12.2.0 进行了验证。
设置项目
您可以使用 @angular/cli 创建一个新的 Angular 项目。
在您的终端窗口中,使用以下命令:
ng new AngularBreakpointsExample --style=css --routing=false --skip-tests
这将配置一个新的 Angular 项目,其样式设置为“CSS”(与“Sass”、“Less”或“Stylus”相对)、无路由和跳过测试。
导航到新创建的项目目录:
cd AngularBreakpointsExample
接下来,安装 @angular/cdk:
npm install @angular/cdk@12.2.0
然后导入布局模块并将其添加到 NgModule 的导入列表中:
src/app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { LayoutModule } from '@angular/cdk/layout';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
LayoutModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
您现在可以开始使用组件中的可用服务和实用程序。 让我们讨论它们中的每一个。
使用 BreakpointObserver.observe 和 BreakpointState
observe 方法返回一个 BreakpointState 类型的可观察对象,可用于观察视口何时在匹配媒体查询之间发生变化。
这是一个示例,如果视口大小在小于 500 像素和等于或大于 500 像素之间发生变化,则会将消息记录到控制台:
src/app/app.component.ts
import { Component, OnInit } from '@angular/core';
import {
BreakpointObserver,
BreakpointState
} from '@angular/cdk/layout';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(public breakpointObserver: BreakpointObserver) {}
ngOnInit() {
this.breakpointObserver
.observe(['(min-width: 500px)'])
.subscribe((state: BreakpointState) => {
if (state.matches) {
console.log('Viewport width is 500px or greater!');
} else {
console.log('Viewport width is less than 500px!');
}
});
}
}
注意: 您可能还需要从 app.component.html 中删除 模板:Title 以防止出错。
BreakpointState 接口为我们提供了一个名为 matches 的布尔属性。
使用 Breakpoints
除了使用手写的媒体查询,我们还可以使用 Breakpoints 对象,它为我们提供了常用断点的键:
src/app/app.component.ts
import { Component, OnInit } from '@angular/core';
import {
BreakpointObserver,
Breakpoints,
BreakpointState
} from '@angular/cdk/layout';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(public breakpointObserver: BreakpointObserver) {}
ngOnInit() {
this.breakpointObserver
.observe([Breakpoints.Small, Breakpoints.HandsetPortrait])
.subscribe((state: BreakpointState) => {
if (state.matches) {
console.log(
'Matches small viewport or handset in portrait mode'
);
}
});
}
}
此示例使用 Breakpoints.Small 和 Breakpoints.HandsetPortrait 的预定义断点。
使用 BreakpointObserver.isMatched
对于一次性匹配,我们可以使用 isMatching method 代替。
src/app/app.component.ts
import { Component, OnInit } from '@angular/core';
import {
BreakpointObserver,
BreakpointState
} from '@angular/cdk/layout';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(public breakpointObserver: BreakpointObserver) {}
ngOnInit() {
if (this.breakpointObserver.isMatched('(min-height: 40rem)')) {
console.log('Viewport has a minimum height of 40rem!');
}
}
}
如果组件初始化时视口至少有 40rem 高,这将记录一条消息。
使用 MediaMatcher
MediaMatcher 是一种围绕 JavaScript 的 matchMedia 的服务。 与 BreakpointObserver.observe 一样,它也可以用于观察视口大小对给定媒体查询的变化。
这是一个检查 min-width 是否为 500px 宽的示例:
src/app/app.component.html
import { Component, OnInit, OnDestroy } from '@angular/core';
import { MediaMatcher } from '@angular/cdk/layout';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
matcher!: MediaQueryList;
constructor(public mediaMatcher: MediaMatcher) {}
ngOnInit() {
this.matcher = this.mediaMatcher.matchMedia('(min-width: 500px)');
this.matcher.addEventListener('change', this.myListener);
}
ngOnDestroy() {
this.matcher.removeEventListener('change', this.myListener);
}
myListener(event: { matches: any; }) {
console.log(event.matches ? 'match' : 'no match');
}
}
与 BreakpointObserver.observe 的区别在于 MediaMatcher 让我们可以访问本机 MatchQueryList 对象,这在某些场景中可能需要。
注: 之前,本例使用了addListener和removeListener。 addListener 已弃用,现代浏览器推荐使用 addEventListener。 并且 removeListener 已被弃用,现代浏览器推荐使用 removeEventListener。
现在,您拥有了在 Angular 中做出反应或调整 UI 以适应不同视口大小所需的一切。
结论
在本文中,在 Angular 项目中应用了 CDK 的布局模块。
继续学习 CDK 的布局模块 API 参考文档。