You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular Material mat-grid-list rowHeight属性TypeScript编译错误求助

解决Angular mat-grid-list rowHeight编译错误

问题根源

你的代码中catchError操作符直接返回字符串"500px",但catchError要求返回Observable类型的值,这会导致rowHeight的Observable类型推断异常,最终让async管道可能输出null,与mat-grid-list的rowHeight属性要求的string | number类型不匹配,触发编译错误。

修复方案

方案1:修正catchError返回值

在catchError中用of()操作符包裹默认值,返回合法的Observable:

import { of } from 'rxjs';
// 其他必要导入...

rowHeight = this.breakpointObserver.observe(Breakpoints.Handset).pipe(
  map(({ matches }) => {
    if (matches) {
      return "1500px";
    }
    return "500px";
  }),
  startWith("500px"),
  catchError(_ => of("500px")) // 返回Observable类型
);

方案2:模板层添加空值兜底

如果不想修改组件逻辑,可在模板中用??空值合并操作符,强制返回合法类型:

<mat-grid-list cols="2" [rowHeight]="(rowHeight | async) ?? '500px'">

方案3:双重保障(推荐)

同时使用上述两种方式,既保证Observable类型正确,又在模板层做兜底:
组件代码:

import { of } from 'rxjs';
import { map, startWith, catchError } from 'rxjs/operators';
// 其他必要导入...

rowHeight = this.breakpointObserver.observe(Breakpoints.Handset).pipe(
  map(({ matches }) => matches ? "1500px" : "500px"),
  startWith("500px"),
  catchError(_ => of("500px"))
);

模板代码:

<mat-grid-list cols="2" [rowHeight]="(rowHeight | async) ?? '500px'">

内容的提问来源于stack exchange,提问作者miaoz2001

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 21:45:08