使用响应式mat-grid-list遇断点错误,请求技术协助
问题解决方案
1. 修复NullInjectorError错误
从错误截图可见,出现NullInjectorError: No provider for BreakpointObserver!,原因是未导入BreakpointObserver所属的模块。
BreakpointObserver来自@angular/cdk/layout,需在AppModule中导入LayoutModule:
import { LayoutModule } from '@angular/cdk/layout'; @NgModule({ imports: [ // ...其他已导入模块 LayoutModule ] }) export class AppModule { }
2. 修正断点布局逻辑异常
当前代码监听[Breakpoints.Handset, Breakpoints.Tablet],只要任一断点匹配matches就返回true,导致平板尺寸下也会使用移动端1列布局(与你提供的尺寸异常截图现象一致)。
调整断点监听与布局映射逻辑,精准区分移动端、平板、桌面端布局:
cardLayout = this.breakpointObserver .observe([ Breakpoints.Handset, Breakpoints.Tablet, Breakpoints.Web ]) .pipe( map(({ breakpoints }) => { // 移动端(手机) if (breakpoints[Breakpoints.Handset]) { return { columns: 1, miniCard: { cols: 1, rows: 1 }, chart: { cols: 1, rows: 2 }, table: { cols: 1, rows: 4 }, }; } // 平板端 else if (breakpoints[Breakpoints.Tablet]) { return { columns: 2, miniCard: { cols: 1, rows: 1 }, chart: { cols: 2, rows: 2 }, table: { cols: 2, rows: 4 }, }; } // 桌面端 else { return { columns: 4, miniCard: { cols: 1, rows: 1 }, chart: { cols: 2, rows: 2 }, table: { cols: 4, rows: 4 }, }; } }) );
逻辑说明
- 放弃依赖
matches,直接判断breakpoints对象中匹配的断点,实现精准的尺寸区分 - 为平板端单独设置2列布局(可根据需求自行调整列数与卡片尺寸)
- 桌面端保留原有4列布局
额外验证点
确保组件中已正确注入BreakpointObserver:
import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout'; constructor(private breakpointObserver: BreakpointObserver) { }
内容的提问来源于stack exchange,提问作者John w.
相关产品推荐
相关产品推荐

