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

导入Angular Material遇NG0203错误:inject()需在注入上下文调用

导入Angular Material时遇"inject() must be called from an injection context..."错误

我是Angular及前端新手,想实现一个仅关注设计的简单表格,参考material.angular.io的示例代码编写后,出现**"inject() must be called from an injection context..."**错误,且仅在添加imports: [MatTableModule]时触发该错误。已尝试调整导入写法、创建app.module.ts替代导入、修改tsconfig.app.json的paths及angular.json相关配置,问题仍未解决。

代码片段

main.ts

import { AppComponent } from './app/app.component';
import { bootstrapApplication } from '@angular/platform-browser';

bootstrapApplication(AppComponent).catch(err => console.error(err));

app.component.ts

import { Component } from '@angular/core';
import { MatTableModule } from '@angular/material/table';

interface brojInfo {
  broj: number,
  ime: string,
  prezime: string
}

var counter: brojInfo[] = [];

for (var i = 0; i <= 1000; i++) {
  counter.push({ broj: i, ime: "Name " + i, prezime: "Surname " + i });
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrl: './app.component.css',
  standalone: true,
  imports: [MatTableModule]
})

export class AppComponent {
  displayedColumns: string[] = ['broj', 'ime', 'prezime'];
  dataSource = counter;
}

app.component.html

<table mat-table [dataSource]="dataSource">
  <ng-container matColumnDef="broj">
    <th mat-header-cell *matHeaderCellDef> Broj </th>
    <td mat-cell *matCellDef="let element"> {{element.broj}} </td>
  </ng-container>

  <ng-container matColumnDef="ime">
    <th mat-header-cell *matHeaderCellDef> Ime </th>
    <td mat-cell *matCellDef="let element"> {{element.ime}} </td>
  </ng-container>

  <ng-container matColumnDef="prezime">
    <th mat-header-cell *matHeaderCellDef> Prezime </th>
    <td mat-cell *matCellDef="let element"> {{element.prezime}} </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 06:32:22