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

Angular使用mat-table报NG0300 th标签匹配多组件如何解决

问题修复方案

错误原因

NG0300错误本质是单个DOM节点(这里是<th>标签)匹配到了多个Angular组件/指令,你的场景下主要是Angular Material表格的解析顺序不符合要求、排序父指令缺失导致的。

修复步骤

  • 调整表格内容的顺序,列定义必须放在行定义之前
    Angular Material Table要求所有<ng-container matColumnDef>列声明必须写在<tr mat-header-row>、<tr mat-row>行声明的前面,否则解析时会出现指令匹配混乱。
  • 给table标签添加matSort指令
    你在表头使用了mat-sort-header排序指令,必须给父级table元素绑定matSort指令才能正常工作,否则会触发指令冲突。
  • 给appliedServices设置初始空数组
    避免异步请求返回前数据源为undefined导致的渲染异常。
  • 确认模块仅导入一次相关依赖
    检查你的模块文件,确保MatTableModule、MatSortModule只导入了一次,没有重复导入也没有引入其他会作用于<th>标签的冲突指令。

修正后的代码示例

TypeScript部分(AppliedServices.ts)

import { Component, Input, OnInit } from '@angular/core';
import { AppliedServiceDto, AppliedServiceService } from '@proxy/applied-services';
import { WorkorderService } from '@proxy/workorders';

@Component({
  selector: 'app-applied-services',
  templateUrl: './applied-services.component.html',
  styleUrls: ['./applied-services.component.scss']
})
export class AppliedServicesComponent implements OnInit {
  @Input() id: string
  // 新增初始空数组
  appliedServices:AppliedServiceDto[] = [];
  columns:string[]=["completedTask","employeeName","actions"];
  constructor(private workorderService:WorkorderService) { }

  ngOnInit(): void {
    this.workorderService.getFullWorkorderDetailsByWorkorderid(this.id).subscribe((work)=>{
      this.appliedServices = work.appliedServices
    });
  }
}

HTML表格部分修正

<table
  mat-table
  [dataSource]="appliedServices"
  matSort <!-- 新增matSort指令 -->
  class="w-100"
>
  <!-- 先写所有列定义 -->
  <ng-container matColumnDef="completedTask">
    <th mat-header-cell *matHeaderCellDef mat-sort-header>
      {{'::Completed Task' | abpLocalization}}
    </th>
    <td mat-cell *matCellDef="let element">{{element.completedTask}}</td>
  </ng-container>

  <ng-container matColumnDef="employeeName">
    <th mat-header-cell *matHeaderCellDef mat-sort-header>
      {{'::Customer' | abpLocalization}}
    </th>
    <td mat-cell *matCellDef="let element">
     {{element.employeeName}}
    </td>
  </ng-container>

  <ng-container matColumnDef="actions">
    <th mat-header-cell *matHeaderCellDef> {{'::Actions' | abpLocalization}} </th>
    <td mat-cell *matCellDef="let element">
      <button mat-raised-button color="primary" [matMenuTriggerFor]="menu" [matMenuTriggerData]="{id: element.id}">
        <mat-icon>settings</mat-icon>
        {{'::Actions' | abpLocalization}}
        <mat-icon>expand_more</mat-icon>
      </button>
    </td>
  </ng-container>

  <!-- 列定义写完再放行定义 -->
  <tr mat-header-row *matHeaderRowDef="columns"></tr>
  <tr mat-row *matRowDef="let myRowData; columns: columns"></tr>
</table>

内容的提问来源于stack exchange,提问作者E. Zahra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 11:36:03