components icon indicating copy to clipboard operation
components copied to clipboard

[Table] Error when using ng-content

Open leibale opened this issue 9 years ago • 17 comments

Bug, feature request, or proposal:

Bug

What is the expected behavior?

md-table should wait until the ng-content replaced.

What is the current behavior?

md-table throws Cannot read property 'getColumnsDiff' of undefined.

What are the steps to reproduce?

Put ng-content inside md-table.

https://plnkr.co/edit/RpOncq9lbwPcjAGjXSyR?p=preview

What is the use-case or motivation for changing an existing behavior?

Anyone that want to create a component with configurable md-table inside cannot do it.

Which versions of Angular, Material, OS, TypeScript, browsers are affected?

Angular: 4.4.0-RC.0 in the plunker, but this is not working with any version. Material: 2.0.0-beta.10

leibale avatar Sep 11 '17 02:09 leibale

I have the same issue. Just want to create component that will unite table, paginator and loading spinner. Now I have to make copy of the same code in each component that have tables

wermetal avatar Oct 10 '17 11:10 wermetal

@wermetal It's possible to create a common component that would have a table, paginator, and spinner. It seems this issue is related more to reusing columns?

@leibale Can you share more about your desired use case? Do you want to create a table that comes with pre-built columns defined but be able to add more columns into the table from ng-content?

andrewseguin avatar Oct 21 '17 00:10 andrewseguin

@andrewseguin exactly

leibale avatar Oct 22 '17 08:10 leibale

@andrewseguin for example i want to make a component to simplify using table (facade pattern) like this:

<eq-table [model]="model3">
  <div eq-cell-detail><div>hello!</div></div>
</eq-table>

and inside the component:

<mat-table #table [dataSource]="dataSource" matSort>
  <ng-container [matColumnDef]="column.name" *ngFor="let column of model.columns">
    <mat-header-cell *matHeaderCellDef matSortHeader>{{column.title}}</mat-header-cell>
    <mat-cell *matCellDef="let element">{{element[column.name]}} </mat-cell>
  </ng-container>
      <!-- Detail Column -->
      <ng-container matColumnDef="details">      
          <mat-cell *matCellDef="let row">
            <ng-container *ngIf="currentRow!==null">
              <ng-content select="[eq-cell-detail]"></ng-content>
            </ng-container>
          </mat-cell>
        </ng-container>
  <mat-header-row *matHeaderRowDef="model.displayedColumns"></mat-header-row>
  <mat-row *matRowDef="let row; columns: model.displayedColumns;" matRipple [style.borderBottomColor]="currentRow == row ? 'transparent' : ''"
            (click)="currentRow = row;"></mat-row>
    <mat-row *matRowDef="let row; columns: ['details']; when: isDetailRow"
            [@detailExpand]="row.data == currentRow ? 'expanded' : 'collapsed'"
    style="overflow: hidden">
  </mat-row>
</mat-table>

eqbalsajadi avatar Oct 22 '17 19:10 eqbalsajadi

Quick update on this PR - it is now possible to directly register columns and rows to the table which means it is possible to create wrapper tables and columns.

andrewseguin avatar Jan 11 '18 18:01 andrewseguin

Is there any documentation on how this can be done? I'm trying to create a basic table component (stackblitz version which allows for column and row definitions as content but I always get ** Could not find column with id ""** errors even when setting the column and row definitions in ngAfterContentInit.

update I found a good sample in the demo app here. Please ignore the comment (I'll leave it up with the link for others).

JayChase avatar Jan 30 '18 10:01 JayChase

for the sample demo. Although there is some 'manually', at least it satisfies the demand. well done.

keatkeat87 avatar Apr 05 '18 09:04 keatkeat87

Thanks for the demo, it is working. I would like to go a bit further with my table component and give the option to define the template of the cell through ng-content.

My table:

<my-table [data]="data" [multisort]="true" [pagination]="true">
  <my-table-column name="id" sortable>
    test id
  </my-table-column>
  <my-table-column name="title">
    test title
  </my-table-column>
</my-table>

My column:

<ng-container matColumnDef>
  <th mat-header-cell *matHeaderCellDef> {{label || name}} </th>
  <td mat-cell *matCellDef="let data"> 
    <ng-content></ng-content>
  </td>
</ng-container>

This is not working, only the last row is displaying the value. How can I make it work and if it is possible how can I pass the data to the ng-content?

catlabs avatar Jun 12 '18 07:06 catlabs

@catlabs I ran into the same issues when I was trying this approach to apply pipes to cell data. Unsure of how I should handle this.

Update: I am applying pipes now on the dataAccessor.

I injected the pipe into my custom table component.

constructor(
  private _datePipe: DatePipe
) { }

getCreatedDate = (data: ViewContactResource) => this._datePipe.transform(data.audit.created, 'short');

Note: Remember that the pipe must be provided in a module, or for custom pipes you can decorate them with the following (Angular 6+).

@Injectable({
  providedIn: 'root'
})

'root' may be replaced with a module if you don't need to provide it everywhere.

natsch93 avatar Jul 02 '18 18:07 natsch93

@catlabs

Finally managed to get ng-content to work inside the column wrapper component.

This is the result.

<app-data-table>

    ...

    <app-data-table-column name="test">
        <ng-template let-data="data">
            {{'Test - ' + data.id}}
        </ng-template>
    </app-data-table-column>

    ...
    
</app-data-table>

All rows are now displaying their id so data is being passed successfully. This is just a basic example, I needed this for my 'Actions' column which contains icons with routerLinks or click events.

Here is what I did.

For ng-content I used ngTemplateOutlet which also allows 'data' to be passed by attaching a context object (See: https://angular.io/api/common/NgTemplateOutlet).

Column wrapper html file:

...
  <td mat-cell
      *matCellDef="let data">

    <ng-content *ngTemplateOutlet="templateRef; context:{data: data}"
                [ngIf]="templateRef"></ng-content>

    <ng-container *ngIf="!templateRef">
      {{getData(data)}}
    </ng-container>

  </td>
...

In the ts file just add templateRef as a ContentChild. Column wrapper ts:

  @ContentChild(TemplateRef) templateRef: TemplateRef<any>;

Hope this helps.

Sources I used to get this far: https://stackoverflow.com/questions/47835488/how-can-i-project-content-to-mat-table-column https://blog.angular-university.io/angular-ng-template-ng-container-ngtemplateoutlet/

Update: Using ContentChild instead of passing template ref as an input.

natsch93 avatar Jul 08 '18 18:07 natsch93

update I found a good sample in the demo app here. Please ignore the comment (I'll leave it up with the link for others).

Any update on this. The link cited above is now a 404. It would be great to be able to project column and row defs via a template.

Update

I found the table-wrapped example and you are able to produce a basic wrapped component following these steps. As in one level away with the mat-table being the direct child of the wrapper and the content being projected directly through ng-content as indicated.

However

It is still not possible to pass the content into the mat-table from a TemplateRef. This results in the same undefined columns error. Doing some more digging, this appears to be related to how angular/core handles the DOM with ContentChildren not getting children from ngTemplateOutlet; #14842

Is there a work around here? Without being able to piece together more complex behaviors we are left out in the cold trying to use Atomic design principles and there is a lot of code duplication.

AndrewPHunter avatar Jan 13 '19 20:01 AndrewPHunter

Updated link to the table-wrapped example: here

BobDankert avatar Mar 18 '20 14:03 BobDankert

update I found a good sample in the demo app here. Please ignore the comment (I'll leave it up with the link for others).

Any update on this. The link cited above is now a 404. It would be great to be able to project column and row defs via a template.

Update

I found the table-wrapped example and you are able to produce a basic wrapped component following these steps. As in one level away with the mat-table being the direct child of the wrapper and the content being projected directly through ng-content as indicated.

However

It is still not possible to pass the content into the mat-table from a TemplateRef. This results in the same undefined columns error. Doing some more digging, this appears to be related to how angular/core handles the DOM with ContentChildren not getting children from ngTemplateOutlet; #14842

Is there a work around here? Without being able to piece together more complex behaviors we are left out in the cold trying to use Atomic design principles and there is a lot of code duplication.

Were you ever able to find a way to pass content from a TemplateRef?

Techgeekster avatar Mar 02 '21 03:03 Techgeekster

Hi, I need to render table conditionally, therefore I can't use { static: true } in @ViewChild(MatTable, {static: true}) table: MatTable<T>; If I switch it to false, the table isn't available until ngAfterViewInit, which is too late for adding row/cols defs. Is there a way around that?

urugator avatar Feb 15 '23 22:02 urugator

@urugator Have you found a workaround for this? 🙏🏻

on3dd avatar Jun 12 '24 05:06 on3dd

Sort of ...

<!--
Have to use class instead of *ngIf to hide table,
otherwise we couldn't use @ViewChild with { static: true },
which is neccessary for this to work.
We can't wrap it with *transloco for the same reason.
 -->
<div [ngClass]="{ hidden: list.pending || list.error }">
  <table mat-table [dataSource]="list.filteredData" [trackBy]="$any(list.trackBy)">
    <ng-content></ng-content>

    <tr class="mat-row" *matNoDataRow>
      <td class="mat-cell" class="py-3" [colSpan]="columnCount">{{ 'noData' | transloco }}</td>
    </tr>
  </table>
</div>

urugator avatar Jun 13 '24 15:06 urugator

Has this bug or whatever it is been resolved yet? I just wanted to have a model table and use it in components. Will I have to copy and paste them every time?

queijobrando avatar Apr 09 '26 20:04 queijobrando