I have a component which have mat-table with data from backend. In this component I have another which is a form for add new element in this data.
It works fine, I can show data in the table, I can add element but after add element my table doesn't refresh data.
Here is my code:
add word:
addWord(): void {
const value = this.addWordForm.value;
console.log(value)
this.wordService.create(value).subscribe(
(word: Word) => {
console.info('Word added');
},
(error: Error) => {
console.error(error);
}
);
create(data: Word): Observable<Word> {
return this.http.post<Word>(this.baseUrl, data);
dataSource:
ngAfterViewInit(): void {
this.wordService.getAll().subscribe(
(data: Word[]): void => {
this.dataSource = new MatTableDataSource(data);
this.dataSource.paginator = this.paginator;
},
(error) => {
console.log(error);
}
);
getAll(): Observable<Word[]> {
return this.http.get<Word[]>(this.baseUrl);
HTML table:
<app-add-word></app-add-word>
<div class="dictionary-table">
<table #table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8">
<!-- Position Column -->
<ng-container matColumnDef="position">
<th mat-header-cell *matHeaderCellDef mat-sort-header> No. </th>
<td mat-cell *matCellDef="let element"> {{dataSource?.filteredData.indexOf(element) + 1}} </td>
</ng-container>
<!-- Polish Column -->
<ng-container matColumnDef="polish">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Polski </th>
<td mat-cell *matCellDef="let element"> {{element.polish}} </td>
</ng-container>
<!-- Spanish Column -->
<ng-container matColumnDef="spanish">
<th mat-header-cell *matHeaderCellDef mat-sort-header> HiszpaĆski </th>
<td mat-cell *matCellDef="let element"> {{element.translated}} </td>
</ng-container>
<!-- Type Column -->
<ng-container matColumnDef="type">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Typ </th>
<td mat-cell *matCellDef="let element"> {{element.type}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<mat-paginator #paginator [pageSizeOptions]="[5, 10, 25, 100]"></mat-paginator>
</div>
addWord(): void { const value = this.addWordForm.value; this.wordService.create(value).subscribe( () => { this.wordService.getAll().subscribe(data => this.dataSource.data = data) }, (error: Error) => { console.error(error); } ); }- Krzysztof Siwek