I have weird case, which I can't go through and don't know how it happen, so I got parent component named SiteComponent
here typescript logic:
ngOnInit(): void {
this.subs.push(
this.route.data.subscribe(data => {
this.siteTemplate$ = this.dataService.getMappedData(`data${data.type}`).pipe(
map(_data => ({..._data, dataType: data.type })),
)
})
);
}
here the template file code:
<div class="app-site">
<ng-container *ngIf="!siteTemplate$ | async">
<div fxLayout="row"
fxLayoutAlign="center"
style="margin-top: 60px;">
<mat-spinner></mat-spinner>
</div>
</ng-container>
<ng-container *ngIf="siteTemplate$ | async">
<app-filters (filtersChanged)="applyFilters()"></app-filters>
<div class="app-site-section">
<div class="app-site-section-column" id="charts">
<app-linear-chart *ngFor="let record of (siteTemplate$ | async)?.chartsData.records"
[categories]="(siteTemplate$ | async)?.chartsData.categories"
[chartData]="record"
></app-linear-chart>
</div>
<div class="app-site-section-column">
<app-pie-chart *ngFor="let record of (siteTemplate$ | async)?.chartsData.records"
[categories]="(siteTemplate$ | async)?.chartsData.categories"
[chartData]="record"
></app-pie-chart>
</div>
</div>
<div>{{siteTemplate$ | async | json}}</div>
<div fxLayout="row"
fxLayoutAlign="center"
id="table"
class="app-site-section"
>
<app-table [tableData]="(siteTemplate$ | async)?.tableData"
[dataType]="(siteTemplate$ | async)?.dataType"
></app-table>
</div>
</ng-container>
</div>
as you can see it consists of few child components, which depends on async pipe, charts works perfect but there is problem with table.
table.ts
export class TableComponent implements AfterViewInit, OnInit {
@Input() tableData: any = {records: []};
@Input() dataType: any;
dataSource: MatTableDataSource<any> ;
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
constructor() {
}
ngOnInit(): void {
console.log(this.tableData);
this.dataSource = new MatTableDataSource(this.tableData.records);
}
ngAfterViewInit(): void {
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
}
}
and here i am getting an error as console.log(this.tableData)
returns null, but the tableData is never null in siteTemplate$
as I checked it by adding tap and logging this value it always appears as object.
You are having multiple siteTemplate$ | async
, each will subscribe to the observable, so siteTemplate$ | async
can be null
.
To prevent it, use siteTemplate$ | async
only once:
<ng-container *ngIf="siteTemplate$ | async as siteTemplate; else other">
...
<app-table [tableData]="siteTemplate.tableData"
[dataType]="siteTemplate.dataType"
></app-table>
</ng-container>
<ng-template #other>
<div fxLayout="row"
fxLayoutAlign="center"
style="margin-top: 60px;">
<mat-spinner></mat-spinner>
</div>
</ng-template>