The ViewChild decorator queries a component's view for a matching child component, directive, or element and exposes the result through a class property. section 29.4.6 section 29.5
Use ViewChild when code needs to work directly with an object created from the component template:
- Access a child component instance in a host test component, then change its inputs and verify component and template output. section 29.4.6
- Access a directive instance so a test can verify how data binding changes affect the directive and its element. section 29.5
- Find an Angular Material paginator and connect it to a table data source after Angular finishes processing the view. section 7.5.3
Querying a paginator
Import ViewChild and MatPaginator, declare a paginator property, and use the view-initialization lifecycle method to associate the queried paginator with the table's data source. The paginator does not exist until Angular has processed the template. section 7.5.3
Listing 7.34. Connecting the paginator in the productTable.component.ts file in the src/app/admin folder
import { Component, IterableDiffer, IterableDiffers, ViewChild }
from "@angular/core";
import { MatTableDataSource } from "@angular/material/table";
import { Product } from "../model/product.model";
import { ProductRepository } from "../model/product.repository";
import { MatPaginator } from "@angular/material/paginator";
@Component({
templateUrl: "productTable.component.html"
})
export class ProductTableComponent {
colsAndRows: string[] = ['id', 'name', 'category', 'price', 'buttons'];
dataSource =
new MatTableDataSource<Product>(this.repository.products());
differ: IterableDiffer<Product>;
constructor(private repository: ProductRepository,
differs: IterableDiffers) {
this.differ = differs.find(this.repository.products()).create();
}
ngDoCheck() {
let changes = this.differ?.diff(this.repository.products());
if (changes != null) {
this.dataSource.data = this.repository.products();
}
}
deleteProduct(id: number) {
this.repository.deleteProduct(id);
}
@ViewChild(MatPaginator)
paginator? : MatPaginator
ngAfterViewInit() {
if (this.paginator) {
this.dataSource.paginator = this.paginator;
}
}
}
Inspect the complete TypeScript pattern for importing ViewChild, querying MatPaginator, and connecting it to MatTableDataSource. section 7.5.3
