英文:
PrimeNG Table filter: Cannot set properties of undefined (setting 'filters')
问题
我需要保存 primeng 表格的过滤状态。我将状态保存到服务中,这方面没有问题。我也从服务中接收数据,并在控制台中显示它们,一切都正常。
但是当我尝试将当前的过滤状态更改为从服务中接收到的状态时,出现了错误。
ERROR TypeError: Cannot set properties of undefined (setting 'filters')
Component.ts
ngOnInit(): void {
const savedFilters = this.fundingService.getDataState();
console.log("savedFilters: ", savedFilters); // 一切正常
if (savedFilters){
this.dt.filters = savedFilters; // 出错
}
}
seeDetailedData(id: string) {
const filters: FilterMetadata[] | FilterMetadata = this.dt.filters;
this.fundingService.setDataState(filters);
this.router.navigate(['test', id]);
}
Component.html
<p-table #dt [value]="data" [paginator]="data.length > 10" [rows]="10" [globalFilterFields]="['name', 'surname']" (sortFunction)="sortPool($event)" [customSort]="true">
<!-- ... -->
</p-table>
Service.ts
private state: any = {};
getDataState(): any {
return this.state;
}
setDataState(newState: any) {
this.state = newState;
}
英文:
I need to save the filtering state of the primeng table. I save the state to the service, there is no problem with that. I also receive data from the service, I display them in the console, everything is fine.
But when I try to change the current filtering state to the one I received from the service, I get an error.
ERROR TypeError: Cannot set properties of undefined (setting 'filters')
Component.ts
ngOnInit(): void {
const savedFilters = this.fundingService.getDataState();
console.log("savedFilters: ", savedFilters); // all is good
if (savedFilters){
this.dt.filters = savedFilters; //error
}
}
seeDetailedData(id: string) {
const filters: FilterMetadata[] | FilterMetadata = this.dt.filters;
this.fundingService.setDataState(filters);
this.router.navigate(['test', id]);
}
Component.html
<p-table #dt [value]="data" [paginator]="data.length > 10" [rows]="10" [globalFilterFields]="['name', 'surname']" (sortFunction)="sortPool($event)" [customSort]="true">
<!-- ... -->
</p-table>
Service.ts
private state: any = {};
getDataState(): any {
return this.state;
}
setDataState(newState: any) {
this.state = newState;
}
答案1
得分: 1
过滤器状态的赋值应该在 ngAfterViewInit
中实现,而不是在 ngOnInit
中。
Component.ts
ngAfterViewInit(): void {
const savedFilters = this.fundingService.getDataState();
console.log("savedFilters: ", savedFilters);
if (savedFilters){
this.dt.filters = savedFilters;
}
}
我认为这与 ViewChild
只有在指令在组件模板中初始化后才可访问有关,而 ngAfterViewInit
在初始化后立即调用。
英文:
Filter state assignment should be implemented in ngAfterViewInit
instead of ngOnInit
Component.ts
ngAfterViewInit(): void {
const savedFilters = this.fundingService.getDataState();
console.log("savedFilters: ", savedFilters);
if (savedFilters){
this.dt.filters = savedFilters;
}
}
I think this is related to the fact that ViewChild
becomes accessible only after the directive is initialized in the component template, and ngAfterViewInit
is called right after its initialization.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论