我想在从ngrx+ api http请求请求数据时进行加载
我有一个包含加载 bool 值的状态,另一个包含原始数据。
当数据到达时,我将加载设置为 false。
问题viewChild
找不到引用,因为数据在加载设置为 false 之前到达。
我收到错误
ERROR TypeError: Cannot read property 'nativeElement' of undefined
这是模板
<div *ngIf="isLoading; else kpi"><mat-spinner></mat-spinner></div>
<ng-template #kpi>
<div class="chartWrapper">
<div class="scrollArea">
<div class="chartAreaWrapper">
<canvas #lineChart id="lineChart" width="1200" height="400"></canvas>
</div>
</div>
<canvas #stickyAxis id="chartAxis" height="400" width="0"></canvas>
</div>
</ng-template>
在组件中
export class BranchKpisComponent implements OnChanges, OnInit, OnDestroy {
@ViewChild('lineChart', { static: true }) private chartRef;
我正在使用 ngrx 商店
我有选择器
selectLoadings$ = this.store.pipe(select(selectLoadings));
selectedDataByBranch$ = this.store.pipe(
select(selectBranchDirections, {
branchId: this.branchId,
location: 'directionsByBranch',
dir: 0
})
里面ngOnchange()
我订阅了加载和数据可观察(单独)
this.selectLoadings$.subscribe(
loading => (this.isLoading = loading.directionsByBranch[this.branchId])
);
this.selectedDataByBranch$
.pipe(filter(data => Object.keys(data).length > 0))
.subscribe(selectedDataByBranch => {
this.trainsDatasets = this.getDatasets(selectedDataByBranch);
this.context = this.chartRef.nativeElement; ### Error undefined chartRef
在 reducer 内部,当我获取数据时,我将加载设置为 false
case ESchedulesActions.GetAllSchedulesByDirectionSuccess: {
return {
...state,
directionsByBranch: {
...state.directionsByBranch,
[action.payload[1]]: action.payload[0]
},
loadings: {
...state.loadings,
directionsByBranch: {
...state.loadings.directionsByBranch,
[action.payload[1]]: false
}
}
};
}
最佳答案
您可以使用 [hidden] 代替 *ngIf。它仍然包含您想要在 DOM 中查看的元素。需要另一个而不是相反的 else。
<div [hidden]="!isLoading"><mat-spinner></mat-spinner></div>
<ng-template [hidden]="isLoading">
<div class="chartWrapper">
<div class="scrollArea">
<div class="chartAreaWrapper">
<canvas #lineChart id="lineChart" width="1200" height="400"></canvas>
</div>
</div>
<canvas #stickyAxis id="chartAxis" height="400" width="0"></canvas>
</div>
</ng-template>
就性能而言,由于代码的大小,根本不会有太大差异。
关于javascript - *ngIf 内的 viewChild 产生 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59785068/