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

Angular RouterLink跳转后页面空白 打开开发者工具才显示问题

问题诱因
  • 硬编码错误:菜品详情模板中mat-grid-list组件的列数属性名拼写错误,Angular Material网格列表的列数输入属性为cols,代码中错写为colums,组件初始化时读取不到合法列数配置,会将网格容器高度计算为0,内部所有内容被折叠隐藏,视觉上呈现空白状态。
  • 渲染触发逻辑缺失:Angular Material组件与Angular Flex Layout布局依赖视口resize事件做尺寸重算,路由跳转完成后没有主动触发全局布局校验,组件会维持初始的0尺寸状态;打开浏览器开发者工具时会修改视口尺寸,自动触发resize事件,组件收到事件后重新计算容器尺寸,内容就会正常渲染。
修复方案
  1. 修正模板属性拼写错误
    找到dishdetail.component.html中的网格列表标签,将错误的属性名替换为正确的cols:
<!-- 错误写法 -->
<!-- <mat-grid-list colums="2" rowHeight=""> -->
<!-- 正确写法 -->
<mat-grid-list cols="2" rowHeight="">
  1. 增加组件初始化时的变更检测触发
    在详情组件中引入变更检测引用,拿到路由参数对应的菜品数据后,手动触发一次变更检测,通知所有布局组件重新计算尺寸,修改dishdetail.component.ts代码如下:
import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';
import { Dish } from '../shared/dish';
import { DishService } from '../services/dish.service';

@Component({
  selector: 'app-dishdetail',
  templateUrl: './dishdetail.component.html',
  styleUrls: ['./dishdetail.component.scss']
})
export class DishdetailComponent implements OnInit {
  dish: Dish;

  constructor(
    private dishService: DishService,
    private route: ActivatedRoute,
    private location: Location,
    private cdr: ChangeDetectorRef
  ) { }

  ngOnInit() {
    const id = this.route.snapshot.params['id'];
    this.dish = this.dishService.getDish(id);
    // 手动触发变更检测,触发布局重算
    this.cdr.detectChanges();
  }

  previousPage(): void {
    this.location.back();
  }
}
  1. 可选校验&优化
  • 检查shared/dishes.ts中菜品数据的id字段类型,如果为数字类型,需要将路由获取到的字符串id转为数字后再做匹配,避免拿不到菜品数据,修改DishService的getDish方法:
getDish(id: string): Dish {
  // id为数字类型时打开下面的转换逻辑
  // const targetId = parseInt(id, 10);
  return DISHES.filter(dish => dish.id === id)[0];
}
  • 模板中的图片地址建议用属性绑定写法,替代插值写法,避免初始加载时src为空的异常:
<img mat-card-image [src]="dish.image" alt="dish">
验证标准

修复完成后点击菜单页的菜品卡片,可直接跳转至详情页看到完整菜品信息、评论列表,返回按钮功能正常,无需打开开发者工具即可正常渲染。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 11:06:19