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

Angular Material 6迁移CustomDateAdapter遇TRIDENT未定义错误求助

解决Angular Material 6中CustomDateAdapter的TRIDENT未定义错误

这个问题我升级Angular Material的时候也碰到过,核心原因就是Material 6对NativeDateAdapter的构造函数做了调整,新增了Platform作为必填的依赖注入项,你的自定义适配器没跟上这个变化才导致的报错。下面是具体的修复步骤:

1. 更新CustomDateAdapter的构造函数

首先在你的custom-date-adapter.ts文件里,先导入Angular CDK提供的Platform类:

import { Platform } from '@angular/cdk/platform';

然后修改你的CustomDateAdapter构造函数,添加Platform参数,并把它和原有的matDateLocale一起传递给父类的构造函数:

export class CustomDateAdapter extends NativeDateAdapter {
  constructor(matDateLocale: string, platform: Platform) {
    // 必须把两个参数都传给父类的构造函数
    super(matDateLocale, platform);
  }

  // 你的其他自定义日期处理方法...
}

2. 在模块中正确配置依赖注入

接下来,在你的根模块(比如AppModule)的providers数组里,要确保CustomDateAdapter能正确获取到Platform实例。你可以通过声明依赖项的方式来配置:

import { NgModule } from '@angular/core';
import { DateAdapter, MAT_DATE_LOCALE } from '@angular/material/core';
import { Platform } from '@angular/cdk/platform';
import { CustomDateAdapter } from './custom-date-adapter';

@NgModule({
  // ...其他模块配置项
  providers: [
    {
      provide: DateAdapter,
      useClass: CustomDateAdapter,
      deps: [MAT_DATE_LOCALE, Platform] // 明确声明依赖的注入顺序和类型
    },
    // 如果你有自定义日期格式,继续配置MAT_DATE_FORMATS即可
    // { provide: MAT_DATE_FORMATS, useValue: YOUR_CUSTOM_DATE_FORMATS }
  ]
})
export class AppModule { }

为什么会出现这个错误?

在Material 6之前,NativeDateAdapter的构造函数只需要接收matDateLocale参数;但升级后,它需要通过Platform类来检测当前运行的浏览器环境(比如判断是否是IE/Trident内核),从而决定是否使用UTC来处理日期显示逻辑。你的旧代码没有传递这个Platform参数,导致父类构造函数里的platform变量为undefined,自然就会抛出Cannot read property 'TRIDENT' of undefined的错误。

按照上面的步骤修改后,你的CustomDateAdapter就能正常适配Material 6的要求了。

内容的提问来源于stack exchange,提问作者René Winkler

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:18:15