Angular material 数据表分页器 returns 使用 Akita Entity Store 插件时未定义

Angular material datatable paginator returns undefined when using Akita Entity Store plugin

我已经被这个问题困扰了两天,希望有人能指出解决方案。我有一个使用 Akita 进行状态管理的 Angular 应用程序,其中一个组件的任务是加载客户列表。我已将我的代码的重要部分放在下面。

// customers.component.ts
export class IndexComponent implements OnInit, AfterViewInit, OnDestroy {
    
    // Constructor and other definitions are here

    customers$: Observable<Customer[]>;
    @ViewChild(MatPaginator) private _paginator: MatPaginator;
    @ViewChild(MatSort) private _sort: MatSort;

    ngOnInit(): void {
        this.customerService.get().subscribe();

        this.customers$ = this._customersQuery.customers$;
    }

    ngAfterViewInit(): void {
        if (this._sort && this._paginator) {
            // Code here is never executed
        }
    }
}

// customer.service.ts
export class CustomerService extends NgEntityService<CustomerState> {
    
    // Constructor is here
    
    get() {
        return this.http.get<Customer[]>('/api/customers').pipe(
            tap(entities => {
                this.CustomerStore.set(entities);
            })
        );
    }
}

// customer.query.ts
export class CustomerQuery extends QueryEntity<CustomerState> {

    public customers$: Observable<Customer[]> = this.selectAll();

    constructor(protected store: CustomerStore) {
        super(store);
    }

}

// customer.component.html
<ng-container *ngIf="(customers$ | async) as customers">
    <ng-container *ngIf="customers.length > 0; else noCustomers">
        // The table goes here
        <mat-paginator>
            // Paginator options go here
        </mat-paginator>
    </ng-container>
</ng-container>

<ng-template #noCustomers><p>No Customers</p></ng-template>

无论我做什么,我总是得到一个 undefined Paginator 实例。我不确定我做错了什么。如有任何帮助,我将不胜感激。谢谢。

问题是您使用 ViewChild 的元素位于 ngIf:

      @ViewChild(MatPaginator) private _paginator: MatPaginator;

当组件初始化时,您尝试绑定的分页器不在 DOM 中,因为它被 ngIf 隐藏,因此绑定不会发生。

关于如何解决这个问题。 TLDR 解决方案是使用绑定到本机 HTML hidden 属性 并翻转你的 ngIf 逻辑。由于 ngIfs 的嵌套和使用 ng-containers 而不是 divs.

,因此您的代码并不那么简单