Material Angular Table ‘child’ component that generates columns

OK, I figured this out finally.

Found this question: Angular Material mat-table define reusable column in component

which led me here:

In short, you have to manually tell the table about the column definitions. This is accomplished by injecting a reference to the MatTable into your child component.

So the constructor for the ‘my-repetitive-columns’ looks like:

constructor(private _table: MatTable<any>) {
  // this._table is a reference to the mat-table element this component is a child of

Then, define a ViewChildren querylist for the new MatColumnDefs in the component:

@ViewChildren(MatColumnDef) columnDefs: QueryList<MatColumnDef>;

Then in ngAfterViewInit():

ngAfterViewInit() {
  this.updateColumnDefs(); // first pass

  // updates ColumnDefs on any changes
  this.columnDefs.changes.subscribe(() => {
  }); //make sure you unsubscribe!

updateColumnDefs() {
  // this attaches the column definition to the table (does nothing about disappearing columns, etc)
  this.columnDefs.forEach((def) => this._table.addColumnDef(def));

I additionally have other function to define the column names, and feed back WHICH of those should be displayed to the table itself (while still letting the parent table component decide which order everything should be in), but that’s specific to my implementation so will leave it out for the purposes of this answer.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top