Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Angular Signals with Material Table data source?

I'm trying to use new angular "feature" - signals. Inside some service I have a signal:

  failedTasks = computed(() => this.tasksState().failedTasks);

And then, I want to connect that signal to the table data source inside component. Previously, using observables, the code was like that:

dataSource = new MatTableDataSource<FailedTask>([]);

constructor(tasksService: TasksService){
    this.tasksService.failedTasks$.subscribe(tasks => this.dataSource.data = tasks)    
}

but with signals I have no idea how to do the same except using "effect" like that:

  constructor(tasksService: TasksService) {
    effect(() => {
      this.dataSource.data = this.tasksService.failedTasks();
    });
  }

What do you think about this approach? According to official docs "Effects are rarely needed in most application code", but how to implement the logic when we need to subscribe some source inside component.ts?

like image 722
Oleksii Yurchenko Avatar asked Mar 18 '26 14:03

Oleksii Yurchenko


1 Answers

Maybe this could be a solution:

export class MyComponent implements AfterViewInit {
  displayedColumns: string[] = ['col1', 'col'];
  dataSource = computed(() => {
    const notifications = this.store.notifications();
    const table = new MatTableDataSource(notifications);
    this.setSortingAndPagination(table);
    return table;
  });

  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatPaginator) paginator: MatPaginator;
  store = inject(NgrxStore);

  ngAfterViewInit(): void {
    this.setSortingAndPagination(this.dataSource());
  }

  setSortingAndPagination(dataSource: MatTableDataSource<Notification>): void {
    dataSource.sort = this.sort;
    dataSource.paginator = this.paginator;
  }
}
  <div class="mat-elevation-z8">
    <table mat-table [dataSource]="dataSource()" matSort>
like image 102
Iurie Marchitan Avatar answered Mar 21 '26 11:03

Iurie Marchitan