Html component
<div>{{ dataTable | json }}</div> This line prits out data normally
<div class="table-container">
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container matColumnDef="userid">
<th mat-header-cell *matHeaderCellDef> userid </th>
<td mat-cell *matCellDef="let element"> {{element.userId}} </td>
</ng-container>
<ng-container matColumnDef="id">
<th mat-header-cell *matHeaderCellDef> id </th>
<td mat-cell *matCellDef="let element"> {{element.id}} </td>
</ng-container>
<ng-container matColumnDef="title">
<th mat-header-cell *matHeaderCellDef> title </th>
<td mat-cell *matCellDef="let element"> {{element.title}} </td>
</ng-container>
<ng-container matColumnDef="completed">
<th mat-header-cell *matHeaderCellDef> completed </th>
<td mat-cell *matCellDef="let element"> {{element.completed}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<mat-paginator [pageSizeOptions]="[2, 4, 6]"
showFirstLastButtons>
</mat-paginator>
</div>
Ts component
import { AfterViewInit, Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { Observable, Subject, takeUntil } from 'rxjs';
import { RandomApiService } from 'src/app/services/RandomAssApi/random-api.service';
import {MatTableDataSource} from '@angular/material/table';
import {MatPaginator} from '@angular/material/paginator';
@Component({
selector: 'app-random-stuff',
templateUrl: './random-stuff.component.html',
styleUrls: ['./random-stuff.component.css']
})
export class RandomStuffComponent implements OnDestroy, AfterViewInit {
private readonly _unsubscribeSub: Subject<void>
public displayedColumns = ['userid','id','title','completed'];
public random: Observable<any>;
public dataTable: any;
public dataSource: MatTableDataSource<any>;
@ViewChild(MatPaginator) paginator: MatPaginator;
constructor(private readonly randomService: RandomApiService) {
this._unsubscribeSub = new Subject<void>();
this.random = this.randomService.data;
this.random.pipe(
takeUntil(this._unsubscribeSub)).subscribe((data) => {
this.dataTable = data;
});
}
ngAfterViewInit(): void {
this.dataSource = new MatTableDataSource(this.dataTable);
this.dataSource.paginator = this.paginator;
}
ngOnDestroy(): void {
this._unsubscribeSub.next();
this._unsubscribeSub.complete();
}
updateData(data: any): void {
this.randomService.postData(data).pipe(
takeUntil(this._unsubscribeSub)).subscribe();
}
}