In Angular, if you're using the new Signal-based toSignal pattern and want to bind it to a MatTableDataSource for use with mat-table, there are a couple of things to keep in mind:
MatTableDataSource expects an Observable or an initial array.
Signals (Signal<T>) are not observables, so they can't be directly assigned to MatTableDataSource.
✅ Solution: Convert Signal to Observable
You can convert your signal into an observable using the asReadonly helper from @angular/core/rxjs-interop.
Here's how you can do it:
1. Import necessary modules:
ts
import { toSignal } from '@angular/core';
import { asReadonlySignal } from '@angular/core/rxjs-interop';
import { MatTableDataSource } from '@angular/material/table';
This gives you an Observable<Subscription[] | undefined>.
4. Create the MatTableDataSource:
ts
dataSource = new MatTableDataSource<Subscription>();
constructor() {
// Connect the observable to the dataSource
this.fetchSubscriptions$.subscribe(data => {
this.dataSource.data = data ?? [];
});
}
Now, whenever the signal changes (e.g., after fetching subscriptions), the table will update automatically.
🧠 Alternative: Use effect() to update dataSource on signal change
If you prefer using Angular's reactive primitives more directly:
ts
constructor() {
effect(() => {
const data = this.fetchSubscriptions();
this.dataSource.data = data ?? [];
});
}
This way, every time fetchSubscriptions() updates, the effect runs and updates the dataSource.
✅ Final Notes
Always default to an empty array (data ?? []) when assigning to dataSource.data to avoid issues with undefined.
You don't need to unsubscribe from effect() — Angular handles that automatically based on the lifecycle context.
Full Example
ts
import { Component, effect, toSignal } from '@angular/core';
import { SubscriptionService } from './subscription.service';
import { Subscription } from './models';
import { MatTableDataSource } from '@angular/material/table';
@Component({
selector: 'app-subscriptions',
templateUrl: './subscriptions.component.html'
})
export class SubscriptionsComponent {
readonly fetchSubscriptions = toSignal(
this.#subscriptionService.fetchSubscriptions()
);
dataSource = new MatTableDataSource<Subscription>();
constructor(private readonly #subscriptionService: SubscriptionService) {
effect(() => {
const data = this.fetchSubscriptions();
this.dataSource.data = data ?? [];
});
}
}
Let me know if you also want to add filtering, sorting, etc. to the table!