Angular Material动态表格排序报错TS2339:BehaviorSubject无sort属性
Hey there! Let's figure out why that sorting isn't working and get it fixed for you.
The Root of the Error
The error TS2339: Property 'sort' does not exist on type 'BehaviorSubject<AbstractControl[]>' makes total sense here. Angular Material's MatTable expects its dataSource to be an instance of MatTableDataSource—a special class built for the table with built-in support for sorting, filtering, and pagination—but you're directly using a BehaviorSubject as your data source. A BehaviorSubject is just an observable stream of data—it doesn't have the sort property the table needs to hook into sorting functionality.
Step-by-Step Fix
Here's how to adjust your code to get sorting working while keeping your dynamic add/remove functionality:
- Define a
MatTableDataSourceinstance in your component, alongside your existingBehaviorSubject:
import { MatTableDataSource } from '@angular/material/table'; import { BehaviorSubject } from 'rxjs'; import { AbstractControl } from '@angular/forms'; // ... dataSource: MatTableDataSource<AbstractControl>; private dataSubject = new BehaviorSubject<AbstractControl[]>([]);
- Subscribe to your
BehaviorSubjectto update theMatTableDataSourcewhenever your data changes (this handles your dynamic add/remove functionality):
ngOnInit() { this.dataSubject.subscribe(updatedData => { this.dataSource = new MatTableDataSource(updatedData); // If the sort is already initialized, bind it here too if (this.matSort) { this.dataSource.sort = this.matSort; } }); }
- Bind the
MatSortinngAfterViewInit(this ensures the sort directive is fully initialized before we attach it):
import { ViewChild } from '@angular/core'; import { MatSort } from '@angular/material/sort'; // ... @ViewChild(MatSort) matSort!: MatSort; ngAfterViewInit() { // Make sure dataSource exists before assigning sort if (this.dataSource) { this.dataSource.sort = this.matSort; } }
- Update your template to use the
MatSortdirective correctly (ensure your column headers include themat-sort-headerdirective to enable clickable sorting controls):
<table mat-table [dataSource]="dataSource" matSort> <!-- Example column with sorting: --> <ng-container matColumnDef="yourColumnName"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Your Column </th> <td mat-cell *matCellDef="let element"> {{ element.value.yourProperty }} </td> </ng-container> <!-- ... rest of your table structure --> </table>
Key Notes
- When you add or remove rows, just update the value of your
BehaviorSubject(e.g.,this.dataSubject.next(newArrayOfControls)), and the subscription will automatically refresh theMatTableDataSource—sorting will stay intact. - Double-check that all columns you want sortable have the
mat-sort-headerattribute on their header cells.
That should resolve the error and get your table sorting working as expected!
内容的提问来源于stack exchange,提问作者anurag07

