As show below code i want to add space after every value in listing in angular. This data are come in table view.
In HTML file
<ng-container matColumnDef="rType">
<th mat-header-cell *matHeaderCellDef > Resource Type </th>
<td mat-cell *matCellDef="let element"> {{element.rType}} </td>
</ng-container>
In ts file
bindTableCol() : void {
if(DNHelper.loginUserData && DNHelper.loginUserData.resourcePreference1 && DNHelper.loginUserData.resourcePreference1.length > 0){
this.displayedColumns = DNHelper.getColumnTable(DNHelper.loginUserData.resourcePreference1);
this.displayedColumns.push('view_more');
this.displayedColumns.push('action');
} else {
this.displayedColumns = ['divisonName', 'categoryName', 'rType', 'resourceStatus', 'view_more', 'action'];
}
}
In Result (These are values)
CRWT1,CRWT2IA,CRWT2,CRWT3,ENG1
Expected Result
CRWT1, CRWT2IA, CRWT2, CRWT3, ENG1
There snap of generated html
To minimize the load on your application, you might also consider creating a pipe.
It could look something like this, as far as usage: <p>{{ element.rType|join:', ' }}</p>.
The transform function would look like this:
#Pipe({
name: 'join'
})
export class JoinPipe implements PipeTransform {
transform(input:Array<any>, sep = ','): string {
return input.join(sep);
}
}
You can try this :
<ng-container matColumnDef="rType">
<th mat-header-cell *matHeaderCellDef > Resource Type </th>
<td mat-cell *matCellDef="let element"> {{element.rType.split(",").join(", ")}} </td>
</ng-container>
Use this code It will help you.
<ng-container matColumnDef="rType">
<th mat-header-cell *matHeaderCellDef > Resource Type </th>
<td mat-cell *matCellDef="let element"> {{element.rType.replaceAll(',',', '}} </td>
</ng-container>
Related
This question already has an answer here:
Mat Table:-How to get one particular element of a particular row on a button click in Mat table angular?
(1 answer)
Closed yesterday.
I have an array of objects that I am using to make a table in Angular. The table works great and adds the data correctly. I am now wanting to be able to edit each object within the table. For example if I wanted to change John Smiths name. How would I make each object in the array its own element so that I can make changes to them individually? Right now if I check 'this.dataFromQuery' it brings back the entire result.
Array: `[
{ first_name: 'John ', last_name: 'Smith', jobNumber: 123 },
{ first_name: 'Smith', last_name: 'John', jobNumber: 321 },
{ first_name: 'Alex', last_name: 'Mason', jobNumber: 10101 },
{ first_name: 'Mason', last_name: 'Alex', jobNumber: 100101 }
]`
Table HTML `
<table mat-table [dataSource]="dataFromQuery.result" class="mat-elevation-z8">
<ng-container matColumnDef="first_name">
<th mat-header-cell *matHeaderCellDef>First Name</th>
<td mat-cell *matCellDef="let element"> {{element.first_name}} </td>
</ng-container>
<ng-container matColumnDef="last_name">
<th mat-header-cell *matHeaderCellDef>Last Name </th>
<td mat-cell *matCellDef="let element"> {{element.last_name}} </td>
</ng-container>
<ng-container matColumnDef="job_Number">
<th mat-header-cell *matHeaderCellDef> Job Number </th>
<td mat-cell *matCellDef="let element"> {{element.jobNumber}} </td>
</ng-container>
<ng-container matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef> Actions </th>
<td mat-cell *matCellDef="let element">
<button (click)="openDialog()" mat-mini-fab color="primary" aria-label="Example icon button with a menu icon">
<mat-icon>edit</mat-icon>
</button>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>"
`
TS
getDataFromAPi(){
this.service.showDataToClient().subscribe((response) => {
console.log("Query Results ", response)
this.dataFromQuery = response
return this.dataFromQuery.result
}, (error) => {
console.log("error", error)
})
}
You already have the "current" row element at hand. All you need to do ti is pass it into the click handler and edit the signature of the method:
<table mat-table [dataSource]="dataFromQuery.result" class="mat-elevation-z8">
...
<ng-container matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef> Actions </th>
<td mat-cell *matCellDef="let element"> <!--- Here you have the row data as "element". Pass it to the "click" handler next line: -->
<button (click)="openDialog(element)" mat-mini-fab color="primary" aria-label="Example icon button with a menu icon">
<mat-icon>edit</mat-icon>
</button>
</td>
</ng-container>
</table>"
Inside your .ts file you need to edit the signature:
openDialog(element: SomeType) {}
Here's the scenarios:
I have a table that displays dealer information, and one of the columns in the table is agents name.
I'm looking to create a table filter that filters the table based on agent name. For the filter I'm using a Select option set that looks like this.
UI:
HTML Code for select:
<div>
<button mat-raised-button class="filter"
(click)=select.open()
>
<mat-icon style="margin-right: 5px;">filter_list</mat-icon>
FIlter by Agent
</button>
<div class="mat-select-wrapper">
<mat-select #select [formControl]="agentsControl" multiple disableOptionCentering panelClass="myPanelClass">
<mat-option *ngFor="let agent of agentsList" [value]="agent">{{agent}}</mat-option>
</mat-select>
</div>
TS Code for Select drop down:
agentsControl = new FormControl();
agentsList: string[] = ['John Doe', 'Mary Jane', 'Johannah Kiffin', 'Eldin Astbery', 'Stephen Curry', 'Chris Smith'];
Here is the code for the table:
HTML Code:
<div flexLayout>
<mat-card>
<div class="table-container">
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8" aria-label="Dealer Queue table">
<ng-container matColumnDef="dealer_id">
<th scope="col" mat-header-cell *matHeaderCellDef>Dealer #</th>
<td mat-cell *matCellDef="let el"> {{el.dealer_id}} </td>
</ng-container>
<ng-container matColumnDef="dealership_name">
<th scope="col" mat-header-cell *matHeaderCellDef>Dealership</th>
<td mat-cell *matCellDef="let el"><a [routerLink]="['dreams-account-page',el.dealer_id]">{{el.dealership_name}} </a></td>
</ng-container>
<ng-container matColumnDef="agent_name">
<th scope="col" mat-header-cell *matHeaderCellDef>Agent</th>
<td mat-cell *matCellDef="let el"> {{el.agent_name}} </td>
</ng-container>
<ng-container matColumnDef="state">
<th scope="col" mat-header-cell *matHeaderCellDef>State</th>
<td mat-cell *matCellDef="let el"> {{el.state}} </td>
</ng-container>
<ng-container matColumnDef="phone_number">
<th scope="col" mat-header-cell *matHeaderCellDef>Phone</th>
<td mat-cell *matCellDef="let el"> {{el.phone_number}} </td>
</ng-container>
<ng-container matColumnDef="total_cancellations">
<th scope="col" mat-header-cell *matHeaderCellDef>Cancellations</th>
<td mat-cell *matCellDef="let el"> {{el.total_cancellations}} </td>
</ng-container>
<ng-container matColumnDef="cancellations_over_120_days">
<th scope="col" mat-header-cell *matHeaderCellDef>Cancellations > 120 Days</th>
<td mat-cell *matCellDef="let el"> {{el.cancellations_over_120_days}} </td>
</ng-container>
<ng-container matColumnDef="total_titles_outstanding">
<th scope="col" mat-header-cell *matHeaderCellDef>Titles</th>
<td mat-cell *matCellDef="let el"> {{el.total_titles_outstanding}} </td>
</ng-container>
<ng-container matColumnDef="titles_over_90_days">
<th scope="col" mat-header-cell *matHeaderCellDef>Titles > 90 Days</th>
<td mat-cell *matCellDef="let el"> {{el.titles_over_90_days}} </td>
</ng-container>
<ng-container matColumnDef="last_contact_date">
<th scope="col" mat-header-cell *matHeaderCellDef>Days Since Last Contact</th>
<td mat-cell *matCellDef="let el"> {{el.last_contact_date | daysSinceToday}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let dqrow; columns: displayedColumns" (click)="openBottomSheet(dqrow)"></tr>
</table>
</div>
<mat-paginator #paginator [pageSizeOptions]="[10, 20, 50, 100, 200, 500]" showFirstLastButtons></mat-paginator>
</mat-card>
</div>
TS for table:
data: DealerQueueTable[] = [];
displayedColumns: string[] = [
'dealer_id',
'dealership_name',
'agent_name',
'state',
'phone_number',
'total_cancellations',
'cancellations_over_120_days',
'total_titles_outstanding',
'titles_over_90_days',
'last_contact_date',
];
dataSource = new MatTableDataSource(this.data);
private subscriptionToDealerQueueTable : Subscription;
constructor(private dreamsService : DreamsService) { }
ngOnInit(): void {
this.subscriptionToDealerQueueTable = this.dreamsService.getDealerQueue().subscribe( dealerQueue => {
this.dataSource.data = dealerQueue;
})
}
#ViewChild('paginator') paginator: MatPaginator;
ngAfterViewInit() {
this.dataSource.paginator = this.paginator;
}
ngOnDestroy() {
this.subscriptionToDealerQueueTable?.unsubscribe();
}
}
Table Model Code:
export interface DealerQueueTable {
dealer_id : number,
dealership_name : string,
agent_name : string,
state : string,
phone_number : number,
total_cancellations : number,
cancellations_over_120_days : number,
total_titles_outstanding : number,
titles_over_90_days : number,
last_contact_date : Date,
market_manager : string,
market_manager_phone : string,
market_manager_email : string
}
Both are child components that share a common parent.
Here's an image of the folder structure:
So basically what I'm trying to do and can't figure out how to do is rather than populating the option set array "agentsList" manually, I'm trying to figure out how this can be done dynamically and programmatically? Where all the unique agent names present in table column agent are passed as values to the option set array.
Here's how I was able to solve this:
In the API call for the table data I retrieved the list of unique agent names and emitted it to the parent component:
Dealer Table TS:
#Output() agentData = new EventEmitter<string[]>();
ngOnInit(): void {
this.subscriptionToDealerQueueTable = this.dreamsService.getDealerQueue().subscribe( dealerQueue => {
//Set the dealerQueue value to this.unfilteredData so we can alter it and still access it later.
this.unfilteredData = dealerQueue;
//Call method to set the this.datasource.data based on given filters.
this.setDataSource(this.unfilteredData, this.FilterValues?.value || []);
let uniqueAgentList = [...new Set(dealerQueue.map(item => item.agent_name))];
this.agentData.emit(uniqueAgentList);
})
this.subscriptionToOptionSetValueChanges = this.FilterValues.valueChanges.subscribe( x => {
this.setDataSource(this.unfilteredData, x || []);
});
}
Using the spread (...) operator and Set operator in javascript we are able to get the unique set of values from the data returned by the api. I then emitted this value to the parent component.
Spread Operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
Set Operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
Parent HomeComponent.html
<div fxFlexOffset="2%" >
<div class="element-header">Dealer Queue Table</div>
<app-filter #FilterDropdown [agentsListOptions]="agentList" ></app-filter>
<app-dealer-queue-table
*ngIf = "FilterDropdown?.agentsControl"
(agentData)="getUniqueAgentData($event)"
class="dealerqueuetable"
[FilterValues]="FilterDropdown?.agentsControl"
></app-dealer-queue-table>
</div>
Parent Home.Component.ts
export class HomeComponent implements OnInit {
agentList = [];
constructor() { }
ngOnInit(): void {
}
getUniqueAgentData(data : any) {
this.agentList = data;
}
}
The event binding, '(agentData)="getUniqueAgentData($event)', connects the event in the child, this.agentData.emit(uniqueAgentList), to the method in the parent, getUniqueAgentData(data : any) {
this.agentList = data;
}.
Now that we have a unique list of agents stored in agentList=[]; in our parent component we pass [agentsListOptions]="agentList" as in input back to the child FilterComponent.
Home.component.html
<app-filter #FilterDropdown [agentsListOptions]="agentList" ></app-filter>
Receive agentListOptions as an input in the filter component:
filter.component.ts
#Input() agentsListOptions: string[];
And finally use it to populate your dropdown options in the html
<mat-select [formControl]="agentsControl" multiple>
<mat-option *ngFor="let agent of agentsListOptions" [value]="agent">{{agent}
</mat-option>
</mat-select>
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.
I have a Nested JSON and I want to output it to Mat-Table... Can you guys help me with this, please?
I can output the json susa, how do I output mandantKagAccountEntity?
My code:
// Nested JSON
{
"success": true,
"susa": [
{
"accountlinevaluesId": 1,
"accountlineId": 1,
"mandantKagId": 660,
"mandantAccountsId": 1,
"period": "7",
"accountNumber": 27,
"name": "EDV-Hardware/Software",
"amount": 55.16859,
"mandantKagAccountEntity": {
"mandantKagId": 660,
"mandantId": 1,
"kagNumber": 2000,
"kagText": "A. I. 1. EDV-Software"
}
},
] }
// test.component.ts
private loadData() {
const yearString = this.year ? `${this.year}` : `${new Date().getFullYear()}`;
this.balanceListService.getDataForAllMonth(yearString).subscribe(
(resp: any) => {
const data = resp.success ? resp.susa : null;
if (null !== data && data) {
.... }
}
}
It depends what exactly you want to pass to mat-table.
If it's an array of the nested property mandantKagAccountEntity, then this should do the trick:
const data = resp.success ? resp.susa.map((item) => item.mandantKagAccountEntity) : null;
If you only want the very first occurrence of mandantKagAccountEntity, then you don't have to iterate over the entire nested object:
const data = resp.success ? resp.susa[0]?.mandantKagAccountEntity : null;
// EDIT: OP had a misleading question. He actually wants to display the entire data, including the nested object. Here's the answer to that:
displayedColumns is being used by mat-table to define which columns to show. You can edit the names to your liking.
displayedColumns: string[] = [
'accountlinevaluesId',
'accountlineId',
'mandantKagId',
'mandantAccountsId',
'period',
'accountNumber',
'name',
'amount',
'mandantKagAccountEntity-mandantKagId',
'mandantKagAccountEntity-mandantId',
'mandantKagAccountEntity-kagNumber',
'mandantKagAccountEntity-kagText',
];
Each column needs a container inside the mat-table that defines how to display the property:
<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" -->
<ng-container matColumnDef="accountlinevaluesId">
<th mat-header-cell *matHeaderCellDef> accountlinevaluesId</th>
<td mat-cell *matCellDef="let element"> {{element.accountlinevaluesId}}</td>
</ng-container>
<ng-container matColumnDef="accountlineId">
<th mat-header-cell *matHeaderCellDef> accountlineId</th>
<td mat-cell *matCellDef="let element"> {{element.accountlineId}}</td>
</ng-container>
<ng-container matColumnDef="mandantKagId">
<th mat-header-cell *matHeaderCellDef> mandantKagId</th>
<td mat-cell *matCellDef="let element"> {{element.mandantKagId}}</td>
</ng-container>
<ng-container matColumnDef="mandantAccountsId">
<th mat-header-cell *matHeaderCellDef> mandantAccountsId</th>
<td mat-cell *matCellDef="let element"> {{element.mandantAccountsId}}</td>
</ng-container>
<ng-container matColumnDef="period">
<th mat-header-cell *matHeaderCellDef> period</th>
<td mat-cell *matCellDef="let element"> {{element.period}}</td>
</ng-container>
<ng-container matColumnDef="accountNumber">
<th mat-header-cell *matHeaderCellDef> accountNumber</th>
<td mat-cell *matCellDef="let element"> {{element.accountNumber}}</td>
</ng-container>
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef> name</th>
<td mat-cell *matCellDef="let element"> {{element.name}}</td>
</ng-container>
<ng-container matColumnDef="amount">
<th mat-header-cell *matHeaderCellDef> amount</th>
<td mat-cell *matCellDef="let element"> {{element.amount}}</td>
</ng-container>
<ng-container matColumnDef="position">
<th mat-header-cell *matHeaderCellDef> position</th>
<td mat-cell *matCellDef="let element"> {{element.position}}</td>
</ng-container>
<ng-container matColumnDef="mandantKagAccountEntity-mandantKagId">
<th mat-header-cell *matHeaderCellDef> mandantKagAccountEntity-mandantKagId</th>
<td mat-cell *matCellDef="let element"> {{element.mandantKagAccountEntity.mandantKagId}}</td>
</ng-container>
<ng-container matColumnDef="mandantKagAccountEntity-mandantId">
<th mat-header-cell *matHeaderCellDef> mandantKagAccountEntity-mandantId</th>
<td mat-cell *matCellDef="let element"> {{element.mandantKagAccountEntity.mandantId}}</td>
</ng-container>
<ng-container matColumnDef="mandantKagAccountEntity-kagNumber">
<th mat-header-cell *matHeaderCellDef> mandantKagAccountEntity-kagNumber</th>
<td mat-cell *matCellDef="let element"> {{element.mandantKagAccountEntity.kagNumber}}</td>
</ng-container>
<ng-container matColumnDef="mandantKagAccountEntity-kagText">
<th mat-header-cell *matHeaderCellDef> mandantKagAccountEntity-kagText</th>
<td mat-cell *matCellDef="let element"> {{element.mandantKagAccountEntity.kagText}}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
Considering you do want to show all data, there's no further mapping of the response needed, other than
this.dataSource = resp.success ? resp.susa : null;
I have solved the problem. Again for your understanding :) The code outputs the whole JSON object (including nesting). Hope I can help those of you who have the exact same problem I had.
// Fill the table with data
private loadData() {
this.balanceListService.getDataForAllMonth(yearString).subscribe(
(resp: any) => {
let data = resp.susa;
if (null !== data && data) {
data = data.map((item) => {
const kag = item.mandantKagAccountEntity;
delete item.mandantKagAccountEntity;
return { ...item, ...kag }; // merge two objects into one
});
}
});
}
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>