I want to build a custom table with mat-table where for the last column and for every row I want to define a custom component. This works. But the custom components are for some input, so the user can select some options or type something in.
<mat-table class="mat-elevation-z8" #table [dataSource]='dataSource'>
<ng-container matColumnDef='value'>
<mat-header-cell *matHeaderCellDef>Values</mat-header-cell>
<mat-cell *matCellDef='let row'>
<app-dropdown-element #drop *ngIf="row.value == 'dropdown'" [options$]='row.$options'></app-dropdown-element>
<app-input-element #text *ngIf="row.value == 'text'" [title]=''></app-input-element>
<app-input-number-element #num *ngIf="row.value == 'number'" [number$]='row.$number'></app-input-number-element>
</mat-cell>
</ng-container>
</mat-table>
That is what I get when I load the component outside the table
'selected' value is also correct:
DropdownElementComponent {options$: {…}, selected: "TEST"}
options$: {label: "TEST", options: Array(2), id: "oil-type"}
selected: "TEST"
__proto__: Object
But inside the table, I get an 'undefined'
Thanks for the stackblitz.
You actually touch on a very interesting quirk of the Angular framework... Check out this article for detailed information on it, but essentially, template reference variables are accessible only inside their own template. And when we add the *ngIf
(or any structural directive for that matter, including *matCellDef
), Angular ends up creating a new <ng-template>
, making any template reference variables accessible only in that template.
So when you try to reference "drop" outside of the * directives, it shows up as undefined.