Angular material 2 table - define column using TemplateRef and ngTemplateOutlet - html

I am trying to make reusable material table and I want to use TemplateRef with ngTemplateOutlet to generate columns. In this example I created cards components which is using my material-table component. In cards.component.html I have template of one of my table's column. Running the project will cause an error ERROR TypeError: Cannot read property 'template' of undefined (see console on stackblitz). Is it possible to pass columnt template to my MaterialTableComponent and use it to define column?
<table mat-table [dataSource]="data" class="mat-elevation-z4">
<ng-container
*ngFor="let column of displayedColumnObjects"
[matColumnDef]="column.id"
>
<!-- if where is cellTemplate in table config json, use cellTemplate -->
<ng-container
*ngIf="column.cellTemplate"
[ngTemplateOutlet]="column.cellTemplate"
>
</ng-container>
<ng-container *ngIf="!column.cellTemplate">
<th mat-header-cell *matHeaderCellDef> {{column.title}} </th>
<td mat-cell *matCellDef="let element"> {{element[column.id]}} </td>
</ng-container>
</ng-container>
<tr mat-header-row *matHeaderRowDef="columnsToDisplay"></tr>
<tr mat-row *matRowDef="let row; columns: columnsToDisplay;"></tr>
</table>
UPDATE
I found solution using ngTemplateOutletContext.
<table mat-table [dataSource]="data" class="mat-elevation-z4">
<ng-container
*ngFor="let column of displayedColumnObjects"
[matColumnDef]="column.id"
>
<ng-container
*ngIf="column.cellTemplate"
>
<th mat-header-cell *matHeaderCellDef> {{column.title}} </th>
<td mat-cell *matCellDef="let element">
<ng-template
[ngTemplateOutletContext]="{
element: element[column.id]
}"
[ngTemplateOutlet]="column.cellTemplate">
</ng-template>
</td>
</ng-container>
<ng-container *ngIf="!column.cellTemplate">
<th mat-header-cell *matHeaderCellDef> {{column.title}} </th>
<td mat-cell *matCellDef="let element"> {{element[column.id]}} </td>
</ng-container>
</ng-container>
<tr mat-header-row *matHeaderRowDef="columnsToDisplay"></tr>
<tr mat-row *matRowDef="let row; columns: columnsToDisplay;"></tr>
</table>
See my example

ADD THE FOLLOWING IN THE COMPONENT TO BE RE-USED
In the '.HTML' file:
<ng-container [ngTemplateOutlet] = "yourNameReference"
[ngTemplateOutletContext] = "{$ implicit: {name: 'Arthur', lastName: 'Lemos'}">
</ng-container>
[NgTemplateOutletContext] data will be sent to the parent component. Remembering that '$ implicit' can receive any data you want to send to the PAI component
In the '.ts' file OF THE REUSABLE COMPONENT add the following code WITHIN YOUR CLASS
#ContentChild ('yourNameReference') yourNameReference: TemplateRef <any>;
FATHER COMPONENT (RECEIVES THE RE-USED COMPONENT)
Add the following code to the '.html' file
<ng-template #yourNameReference let-myDataa>
<p> {{myDataa.name}} {{myDataa.lastName}} </p>
</ng-template>
That way you can send data from the child component to the parent component, so you can create dynamic columns for your table.
Just follow the steps above, however, applying the specific columns of the table ... EX:
<td> <ng-container [ngTemplateOutlet] = "yourNameReference"
[ngTemplateOutletContext] = "{$ implicit: {name: 'Arthur', lastName: 'Lemos'}">
</ng-container> </td>
Add to the child's .ts:
#ContentChild ('yourNameReference') yourNameReference: TemplateRef <any>;
In the parent component:
<my-table>
...
<ng-template #yourNameReference let-myDataa>
<p> {{myDataa.name}} {{myDataa.lastName}} </p>
</ng-template>
<! - this content will be rendered inside the table ... ->
...
</my-table>
YOU CAN CREATE A REFERENCE NAME FOR EACH COLUMN, AND REPEAT THE PROCESS
ANGLE VERSION: 9
DOCUMENTATION: https://angular.io/api/common/NgTemplateOutlet
The documentation does not show the use of ngTemplateOutlet in different components, but it already helps in something.

Related

Data is not getting displayed in the html data, when it is stored in db.json

I have stored some data in db.json. In the ts file I have used the get function and received it in a variable. The data is coming through successfully( I checked using console.log). However it is not displaying in the html table i have created.
Below is my html file
<p>people works!</p>
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<!--- Note that these columns can be defined in any order.
The actual rendered columns are set as a property on the row definition" -->
<!-- Position Column -->
<ng-container matColumnDef="id">
<th mat-header-cell *matHeaderCellDef> No. </th>
<td mat-cell *matCellDef="let element; let i = index"> {{i+1}} </td>
</ng-container>
<!-- Name Column -->
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef> Name </th>
<td mat-cell *matCellDef="let element"> {{element.name}} </td>
</ng-container>
<!-- Weight Column -->
<ng-container matColumnDef="company">
<th mat-header-cell *matHeaderCellDef> Comapnay </th>
<td mat-cell *matCellDef="let element"> {{element.company}} </td>
</ng-container>
<!-- Symbol Column -->
<ng-container matColumnDef="email">
<th mat-header-cell *matHeaderCellDef> Email </th>
<td mat-cell *matCellDef="let element"> {{element.email}} </td>
</ng-container>
<ng-container matColumnDef="address">
<th mat-header-cell *matHeaderCellDef> Address </th>
<td mat-cell *matCellDef="let element"> {{element.address}} </td>
</ng-container>
<ng-container matColumnDef="active">
<th mat-header-cell *matHeaderCellDef> Active </th>
<td mat-cell *matCellDef="let element"> {{element.active}} </td>
</ng-container>
<ng-container matColumnDef="action">
<th mat-header-cell *matHeaderCellDef> Action </th>
<td mat-cell *matCellDef="let element; let j = index"><button (click) = "detail(j)"> {{element.action}} </button></td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<div id = "Detail">
{{userDetail.id}}<br>
{{userDetail.name}}<br>
{{userDetail.company}}<br>
{{userDetail.email}}<br>
{{userDetail.active}}<br>
{{userDetail.action}}
</div>
And the next code is my ts file
import { Component, OnInit } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { user } from './userInterface';
#Component({
selector: 'app-people',
templateUrl: './people.component.html',
styleUrls: ['./people.component.css']
})
export class PeopleComponent implements OnInit {
displayedColumns=["id","name","company","email","address","active","action"];
UserDb:user[]=[];
dataSource = this.UserDb;
userDetail: user={
id: 0,
name: '',
company: '',
email: '',
address: '',
active: false,
action: ''
};
detail(rowid: number) {
this.userDetail = this.UserDb[rowid];
}
constructor(private _http: HttpClient) {
}
ngOnInit(): void {
console.log("im working");
this._http.get("http://localhost:3002/posts").subscribe((users:any)=>{
this.UserDb = users;
console.log(this.UserDb);
})
}
}
`
My entire data is being shown in the console.
data in the console. But not showing under the table
It looks that dataSource gets the value of UserDB before UserDB is populated. So, you get valid data in the console; but not in HTML. Why do you use two variables in the first place?
Hi I found the error in the code. Actually, the variables used in json needs to be exactly the same to the one used in the front-end part of the program.Like in my ts code i have used 'id' and 'name'.But in json the same variables I've written as 'Id' and 'Name'. Hence, the problem.

Trying to loop through elements and set styles at same time

I have an angular material table
(HTML)
<table mat-table
[dataSource]="dataSource" multiTemplateDataRows
class="mat-elevation-z8">
<ng-container *ngIf="{{column}}" matColumnDef="{{column}}" *ngFor="let column of displayedColumns">
<th mat-header-cell *matHeaderCellDef> {{column}} </th>
<td mat-cell *matCellDef="let element"> {{element[column]}} </td>
</ng-container>
I want to change the styling on the element if it equals 'Missing' (e.g. {{element[column}} == Missing then change styling).
(style) (HTML)
<mat-chip *ngIf="element.status=='Missing'" style="background-color: #ec9d9d; color: red">Missing</mat-chip>
How can I do this in the HTML? I only want to do this if the displayedColumn 'status' is equal to 'Missing'.
(Typescript)
displayedColumns: string[] = [
'id',
'tradingPartnerTradingPartner',
'fileFormatFileFormat',
'status',
];
you could use the ng-class directive
in your example, using it should be something like this:
(Assuming the mat-chip would get placed into this cell I modified below)
<table mat-table [dataSource]="dataSource" multiTemplateDataRows
class="mat-elevation-z8">
<ng-container *ngIf="{{column}}" matColumnDef="{{column}}" *ngFor="let column of displayedColumns">
<th mat-header-cell *matHeaderCellDef> {{column}} </th>
<td mat-cell *matCellDef="let element"
[ngClass]="{missing: element.status=='Missing' }"> {{element[column]}} </td>
</ng-container>
...
and don't forget to create the css for the .missing class we are referencing in the ngClass directive:
.missing {
background-color: #ec9d9d;
color: red
}

Add a html button to each row dynamically in angular material table

I have done a code to generate a datatable based on dynamic rows and columns. I need to add a html button in the last column of each row for edit. How to do that. Below is the code
<div class="example-table-container" >
<table mat-table [dataSource]="data" class="example-table"
matSort matSortActive="created" matSortDisableClear matSortDirection="desc">
<ng-container *ngFor="let disCol of this.columnHeading | keyvalue; let colIndex = index" matColumnDef="{{disCol.key}}">
<th mat-header-cell *matHeaderCellDef><b>{{disCol.value}}</b></th>
<td mat-cell *matCellDef="let element">{{element[disCol.key]}}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</div>
When i insert html code in value the button is not appearing but only html code is appearing like this
<button>Edit</button>
I have tried the bypassSecurityTrustHtml also. It gives the error safeValue must use [property]=binding:
Angular material table provides a stickyend property with some css.
Normally we add an extra th with stickyend to solve that.
Below is an example of that..
<ng-container matColumnDef="star" stickyEnd>
<th mat-header-cell *matHeaderCellDef></th>
<td mat-cell *matCellDef="let element">
<mat-icon>more_vert</mat-icon>
</td>
</ng-container>
https://stackblitz.com/angular/nneoarrlekb?file=src%2Fapp%2Ftable-sticky-columns-example.html
<table mat-table [dataSource]="data" class="example-table"
matSort matSortActive="created" matSortDisableClear matSortDirection="desc">
<ng-container *ngFor="let disCol of this.columnHeading | keyvalue; let colIndex = index" matColumnDef="{{disCol.key}}">
<th mat-header-cell *matHeaderCellDef ><b >{{disCol.value}}</b></th>
<td mat-cell *matCellDef="let element" [innerHtml]="element[disCol.key]"></td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;">
</tr>
</table>
I have done this using the innerhtml
try to add this
<ng-container matColumnDef="actions">
<mat-header-cell *matHeaderCellDef></mat-header-cell>
<mat-cell *matCellDef="let row">
<button mat-icon-button (click)="onEdit(row)"><mat-icon>launch</mat-icon></button>
<button mat-icon-button color="warn" (click)="onDelete(row.$key)"><mat-icon>delete_outline</mat-icon></button>
</mat-cell>
</ng-container>
do not forget to add this column in displayedColumns
displayedColumns: string[] = ['fullName', 'email', 'mobile', 'city', 'departmentName', 'actions'];
I was in a similar predicament to you and this is what I came up with.
Firstly, trying to add the html button tag as a value is not a solution and akin to html injection.
Given an example set of columns,
const columnHeadings = ['position', 'firstName', 'lastName', 'actions'];
const displayNames = ['No.', 'First Name', 'Last Name', 'Actions'];
we may dynamically populate our table. What I have done here is presented different content for my one column, 'actions', based on a condition that is triggered by the desired column.
<table mat-table [dataSource]="data" class="example-table">
<ng-container matColumnDef="{{disCol}}" *ngFor="let disCol of columnHeadings; index as i">
<th mat-header-cell *matHeaderCellDef> {{displayNames[i]}} </th>
<td mat-cell *matCellDef="let element">
<div *ngIf="column!=='actions'"> {{element[disCol]}} </div>
<div *ngIf="column==='actions'">
<button mat-icon-button>
<mat-icon>edit</mat-icon>
</button>
</div>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="columnHeadings"></tr>
<tr mat-row *matRowDef="let element; columns: columnHeadings;" class="element-row"></tr>
</table>
By no means have a done a very elegant way to execute this but it is one that works; even if it is somewhat of a "hack" solution.

Is there any way to edit specific Column of table using mat-table in Angular material

In my project i am using Angular Material's table for displaying value in table format, As per new requirement i have to perform in-line editing for last 2 column over other along with that if user click 1st column the other column get highlighted automatically and everything has to be done using Angular material
This is the last 2 column i want to perform in-line editing
> <ng-container matColumnDef="weight">
> <th mat-header-cell *matHeaderCellDef> Weight </th>
> <td mat-cell *matCellDef="let element"> {{element.weight}} </td>
> </ng-container>
> <ng-container matColumnDef="symbol">
> <th mat-header-cell *matHeaderCellDef> Symbol </th>
> <td mat-cell *matCellDef="let element"> {{element.symbol}} </td>
> </ng-container>
>
>
> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
> <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr> </table>
How i achieved is as follows :
<tbody>
<tr *ngFor="let data of dataSource">
<td >{{data.position}}</td>
<td >{{data.name}}</td>
<td *ngIf="data.position === editRowId"> <input matInput [(ngModel)]="data.weight"></td>
<td *ngIf="data.position !== editRowId" (click)="editTableRow(data.position)">{{data.weight}}</td>
<td *ngIf="data.position === editRowId"> <input matInput [(ngModel)]="data.symbol"></td>
<td *ngIf="data.position !== editRowId" (click)="editTableRow(data.position)">{{data.symbol}}</td>
</tr>
</tbody>
TS file for above code :
export class AppComponent {
showEditTable = false;
editRowId: any = '';
selectedRow;
displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
dataSource = ELEMENT_DATA;
editTableRow(val) {
console.log('click event started val = ' + val);
this.editRowId = val;
console.log('click event ended with val = ' + val);
}
}
I expect the result as table where last 2 column can be edited inline and at the same time i can send modified data to backend
Naman, it's the same, you need use <ng-container>to avoid create extra tags, so your columns becomes like
<!-- Weight Column -->
<ng-container matColumnDef="weight">
<th mat-header-cell *matHeaderCellDef> Weight </th>
<td mat-cell *matCellDef="let element">
<ng-container *ngIf="element.position!==editRowId">
<span (click)="edit(element.position,'weigth')">{{element.weight}} </span>
</ng-container>
<ng-container *ngIf="element.position===editRowId">
<input matInput name="weigth" [(ngModel)]="element.weight">
</ng-container>
</td>
</ng-container>
Well, I call to function "edit" passign two arguments, the position and a string indicate the "name" of the input attributes. This allow us "focus" the input clicked. how?
We declare a ViewChildren of the MatInputs
#ViewChildren(MatInput,{read:ElementRef}) inputs:QueryList<ElementRef>;
See that we get not the MatInput else the "ElementRef". This allow us, in out function edit get the element with the attributes name equal the string that pass as argument, and focus it. See that we need "enclosed" all in a setTimeout to allow Angular to show the input
edit(row,element)
{
this.editRowId=row;
setTimeout(()=>{
this.inputs.find(x=>x.nativeElement.getAttribute('name')==element)
.nativeElement.focus()
})
}
You can see the full example in stackblitz
Well, in the example the data is hardcoded. Let's go to imagine that the data (and the structure) comes from a service data. The data is easy imagine because it's the same. The "structure" we can imagine as an array of object with three properties: name,head ad fixed. if fixed is true, we only show the data, else we can edit. So the only thing we need is create the columns in a *ngFor
First we are going to see how our schema can be defined. It's only an array
[
{name:'position',head:"No.",fixed:true},
{name:'name',head:"Name",fixed:true},
{name:'weight',head:"Weigth",fixed:false},
{name:'symbol',head:"Symbol",fixed:false},
]
Our table becomes like
<table #table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container *ngFor="let column of schema;let last=last">
<ng-container [matColumnDef]="column.name">
<th mat-header-cell *matHeaderCellDef> {{column.head}} </th>
<td mat-cell *matCellDef="let element">
<ng-container *ngIf="element[schema[0].name]!==editRowId || column.fixed">
<span
(click)="column.fixed?editRowId=-1:
edit(element[schema[0].name],column.name)">
{{element[column.name]}}
</span>
</ng-container>
<ng-container *ngIf="element[schema[0].name]===editRowId && !column.fixed">
<input matInput [id]="column.name"
[(ngModel)]="element[column.name]"
(blur)="last?editRowId=-1:null">
</ng-container>
</td>
</ng-container>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
See that we "replace" element.position by element[column[0].name] -I supouse the first element of the schema will be the "key" and how we using [(ngModel)]="elemen[column.name]". Yes, to refererd to element.position we can refered too as elemen["position"] and remember we are iterating over "schema"
Another thing is that we are going to use "id", not "name". this is because if we using name, really Angular put as attrib some like: ng-reflect-name, and this don't allow us focus the input.
Finally we are get the data in the ngOnInit. We are going to use forkJoin to get together the schema and the data. A forkJoin only call and array of observables (in this case this.dataService.getSchema() and this.dataServide.getData, and return in an array the response of all the observables. We use the way
([variable1,variable2]) to store in "variable1" the first result and in variable2 the second result
ngOnInit()
{
forkJoin([this.dataService.getSchema(),this.dataService.getData()])
.subscribe(([schema,data])=>{
this.dataSource=data;
this.displayedColumns=schema.map(x=>x.name)
this.schema=schema
})
}
The displayedColumns must be an array with the names of the columns, but we need to store in an array the "schema" too.
In the stackblitz I create a service and "simulate" the observable using the rxjs creation operator of, in a real application the data becomes from a httpClient.get(....)

Can I put an ngIf else condition on a Angular Material table?

I've followed the Angular docs here https://angular.io/api/common/NgIf to create an NgIf else conditional over my Material Table. It is reading remote JSON file as API.
The API is twitter data and one of the fields I want to run condition on is 'replies'. If there are no replies, I want to replace the "0" with a "-".
I am getting the error
Can't have multiple template bindings on one element. Use only one attribute prefixed with * (" Replies
]*ngIf="hashtags.replies<1; else noReplies"> {{hashtags.replies}}
"):`
So it seems I cannot run NgIf and interpolate my data in the same element, I've tried all kinds of combinations in the HTML but I am real stuck.
HTML
<ng-container matColumnDef="replies">
<th mat-header-cell *matHeaderCellDef> Replies </th>
<td mat-cell *matCellDef="let hashtags" *ngIf="hashtags.replies<1; else noReplies"> {{hashtags.replies}} </td>
<ng-template #noReplies>-</ng-template>
</ng-container>
Try
<ng-container matColumnDef="replies">
<th mat-header-cell *matHeaderCellDef> Replies </th>
<ng-container *matCellDef="let hashtags">
<td mat-cell *ngIf="(hashtags.replies>0); else noReplies"> {{hashtags.replies}} </td>
</ng-container>
<ng-template #noReplies>-</ng-template>
</ng-container>
The reason for getting this error is because your can't put 2 structural directives on the same DOM
In your code, you were using *matCellDef and *ngIf on the same <td>.
you can do it this way...... xd
<ng-container matColumnDef="estadoRevision">
<mat-header-cell *matHeaderCellDef mat-sort-header>Revision</mat-header-cell>
<mat-cell *matCellDef="let element">
<td *ngIf="element.a === 0"> ejemplo </td>
<td *ngIf="element.a === 1"> ejemplo </td>
</mat-cell>
</ng-container>
Is there any reason you can't do the conditional directly in the interpolation?
<td mat-cell *matCellDef="let hashtags">{{hashtags.replies > 0 ? hashtag.replies : '-'}}</td>