Disable MatSort on space key pressed Angular Material - html

So I'm using angular material tables and decided to made a filter for each column. The inputs for this filters are located in the row header of each column. That works fine, but the thing is when I'm typing and pressed the space key, the table gets sorted. I want this behavior to stop, but if I used (keydown.space)="$event.preventDefault()" but the space isn't inserted in the input. Here is the code below of the table.
<table mat-table class="full-width-table" (matSortChange)="sortData($event)" [dataSource]="this.datasrcCollIndex" aria-label="Elements" matSort matSortActive="strName" matSortDirection="asc" matSortDisableClear>
<!-- Name Column -->
<ng-container matColumnDef="strName">
<th mat-header-cell *matHeaderCellDef mat-sort-header>
<mat-form-field style="margin-top: 0px;">
<input matInput placeholder="Name" (keyup)="filteringByColumns()" [(ngModel)]="strName" >
</mat-form-field>
</th>
<td mat-cell *matCellDef="let user">{{user.strName}}</td>
</ng-container>
<!-- Gender Column -->
<ng-container matColumnDef="strGender">
<th mat-header-cell *matHeaderCellDef mat-sort-header>
<mat-form-field style="margin-top: 0px; width: 70px;">
<input matInput placeholder="Gender" (keyup)="filteringByColumns()" [(ngModel)]="strGenderColumn">
</mat-form-field>
</th>
<td mat-cell *matCellDef="let user">{{user.strGender}}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="this.dictstrDisplayedColumns"></tr>
<tr mat-row (click)="this.showDetailsOfUsers(user)"
*matRowDef="let user; columns: this.dictstrDisplayedColumns;"></tr>
</table>

Instead of using
preventDefault()
I used
stopPropagation()
it still allows input to be entered, but does not propagate the event to the parent elements (thus the sorting element never receiving the event).
Usage:
(keydown.space)="$event.stopPropagation()"

i had the same problem and did:
event.preventDefault();
(event.target as any).value += ' ';

Related

How to bind a text input that's inside a dynamic table?

I have a table where a column is a text input.
When the user edits the text both a save and cancel button became enabled.
The save button should just send the new value to the server. I can do that one no problem.
But the cancel button I can't figure out how to change the input back. Because with both model or a child element how do I know which element of the table I'm writing in?
The template part:
<table mat-table [dataSource]="gsServersDataSource" class="mat-elevation-z8">
<tr mat-header-row *matHeaderRowDef="gsServersHeaders"></tr>
<tr mat-row *matRowDef="let row; columns: gsServersHeaders;"></tr>
<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="value">
<th mat-header-cell *matHeaderCellDef mat-sort-header sortActionDescription="Sort by value"> Value </th>
<td mat-cell *matCellDef="let element">
<input id="valueInput" type="text" value="{{element.value}}" (keyup)="onChangeValue()">
</td>
</ng-container>
<ng-container matColumnDef="modify">
<th mat-header-cell *matHeaderCellDef> Modify </th>
<td mat-cell *matCellDef="let element">
<button id="saveChanges" mat-mini-fab color="primary" (click)="onClickSave()" [disabled]="disabled">
<mat-icon>✓</mat-icon>
</button>
<button id="cancelChanges" mat-mini-fab color="primary" (click)="onClickCancel(element)" [disabled]="disabled">
<mat-icon>X</mat-icon>
</button>
</td>
</ng-container>
</table>
The component part:
gsServersDataSource = [{name: 'name1', value: 'value1'}];
gsServersHeaders: string[] = ['name', 'value', 'modify'];
disabled=true;
onChangeValue(){
this.disabled=false;
}
onClickSave(element: InstanceDataPoint){
//service call with new value
this.disabled=true;
}
onClickCancel(element: InstanceDataPoint){
//Put original back : How to??
this.disabled=true;
}
}
I created another value for each line that contains the temporary value the user inputted.
When the user wants to save it, it will be posted and on success saved as the original value.
When the user wants to cancel the changes. The temporary value will be reset to the original value.
On the template I'm now using the newValue as the value of the text input.
And I'm passing to the keyup hook the inputted value
<ng-container matColumnDef="value">
<th mat-header-cell *matHeaderCellDef mat-sort-header sortActionDescription="Sort by value"> Value </th>
<td mat-cell *matCellDef="let element">
<input id="valueInput" type="text" value="{{element.newValue}}" (keyup)="onChangeValue(element,$event.target.value)">
</td>
</ng-container>
On the component, I'm now saving the inputted value to the newValue on changes to the text input.
On clicking save I'm assigning the newValue to the originalValue if the post is successful.
And on clicking cancel I'm putting the newValue back to the originalValue.
onChangeValue(element: InstanceDataPoint, newValue: string){
element.disabled = false;
element.newValue = newValue;
}
onClickSave(element: InstanceDataPoint){
this.gsInstancesService.postModifiedValue(this.selectedEnvironment,
{ "param-name": element.name, "param-val": element.newValue, "server-id": element.server, "language": element.language}).
subscribe({complete: ()=>element.value=element.newValue});
element.disabled=true;
}
onClickCancel(element: InstanceDataPoint){
element.newValue = element.value;
element.disabled = true;
}

Angular Material Table, multiple filters with each a column

I have build a table in Angular Material with a general filter (I have followed the official documentation for that). For the purpose of my project I would like to have different filter for each column of my table. For example a filter for the column "name" and another filter for the column "amount". How can I achieve this?
html
<mat-form-field appearance="standard" color="accent">
<mat-label>Filter</mat-label>
<input matInput (keyup)="applyFilter($event)" placeholder="Search" #input>
</mat-form-field>
<table mat-table [dataSource]="expense" class="mat-elevation-z8">
<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 | currency:'CHF '}} </td>
</ng-container>
[...]
</table>
typescript
applyFilter(event: Event) {
const filterValue = (event.target as HTMLInputElement).value;
this.dataSource.filter = filterValue.trim().toLowerCase();
}

How to optimize a table in angular material

im trying to show a list of products, and it does, but the problem is it freeze for 6 or 8 seconds, tha size of the register is 2338, im using entity framework to obtain the register, some idea to solve or optimize
this is the method to get the list from the other class and there i obtain from the entity framework
getProveedor(){
this.apiproveedor.getProveedor().subscribe(response=>{
console.log(response.data);
if(response.exito==1){
this.lst=response.data;
this.resultsLength=this.lst.length;
this.dataSource=response.data;
}
});
getProveedor():Observable<Response>{
return this._http.get<Response>(this.url);
}
this is the html, im using a mat table
<!--
-->
<div>
<mat-toolbar >
<span >Pharmacy Lion</span>
<img src="./assets/img/2.png" class="tama">
</mat-toolbar>
<div>
<a mat-raised-button color="primary" (click)="openAdd()">Nuevo Producto</a>
</div>
<mat-form-field appearance="standard">
<mat-label>Filter</mat-label>
<input matInput placeholder="Buscar Nombre" #input (keyup)="applyFilter($event)">
</mat-form-field>
<table mat-table [dataSource]="lst" class="table"
matSort matSortActive="created" matSortDisableClear matSortDirection="desc">
<ng-container matColumnDef ="IdProducto" class="header-align-right"
mat-sort-header disableClear>
<th mat-header-cell *matHeaderCellDef mat-sort-header >#</th>
<td mat-cell *matCellDef="let element">{{element.idProducto}}</td>
</ng-container>
<ng-container matColumnDef ="Nombre" >
<th mat-header-cell *matHeaderCellDef mat-sort-header class="header-align-right" >Nombre Producto</th>
<td mat-cell *matCellDef="let element" class="header-align-right">{{element.nombre}}</td>
</ng-container>
<ng-container matColumnDef ="Cantidad">
<th mat-header-cell *matHeaderCellDef mat-sort-header class="header-align-right"> Cantidad </th>
<td mat-cell *matCellDef="let element" class="header-align-right">{{element.cantidad}}</td>
</ng-container>
<ng-container matColumnDef ="Descripcion">
<th mat-header-cell *matHeaderCellDef mat-sort-header class="header-align-right">Descripcion</th>
<td mat-cell *matCellDef="let element" class="header-align-right">{{element.descripcion}}</td>
</ng-container>
<ng-container matColumnDef ="Precio">
<th mat-header-cell *matHeaderCellDef mat-sort-header class="header-align-right">Precio</th>
<td mat-cell *matCellDef="let element" class="header-align-right">{{element.precio}}</td>
</ng-container>
<ng-container matColumnDef ="Acciones">
<th mat-header-cell *matHeaderCellDef class="header-align-right margencab" >Acciones</th>
<td mat-cell *matCellDef="let element" class="header-align-right ">
<button (click)="Edit(element)" mat-raised-button color="primary" class="margencab">Editar</button>
<button (click)="delete(element)" mat-raised-button color="Basic" class="margencab">Eliminar</button>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="Columnas"></tr>
<tr mat-row *matRowDef="let row; columns Columnas"></tr>
</table>
</div>
You could try implementing lazy loading of data, which is mentioned in material docs.
You can implementing server side pagination. You need to send page size and page number along with your existing query parameters. In this way it will be more scalable no matter how many data you have cause you are dealing with small chunk of data each request.
you can find a lot of examples out there. With a quick search I found this article one that seems easier to understand
You could also try to implement virtual-scroller provided by material angular CDK (Common Development Kit).
You can find the details here.

Add search button in Angular Spring Boot Application

I have the following HTML file to show some values:
<h1 mat-dialog-title color="primary">
License Details
</h1>
<mat-dialog-content >
<div style="width:100%;display: flex;flex-direction: column;">
</div>
</mat-dialog-content>
<mat-dialog-content>
<div class="example-container mat-elevation-z8">
<table mat-table [dataSource]="customerList" class="a">
<ng-container matColumnDef="Customer ID" margin-right:10px margin-left:10px>
<th mat-header-cell *matHeaderCellDef class="customtd" style="font-size:15px;"><strong>Customer Id*</strong></th>
<td mat-cell *matCellDef="let element" class="customtd"> {{element.customerId}} </td>
</ng-container>
<ng-container matColumnDef="Hardware Key" margin-right:10px margin-left:10px>
<th mat-header-cell *matHeaderCellDef class="customtd" style="font-size:15px;"><strong>Hardware Key</strong></th>
<td mat-cell *matCellDef="let element" class="customtd"> <textarea rows="2" cols="20" wrap="hard">{{element.hardwareKey}}</textarea> </td>
</ng-container>
<ng-container matColumnDef="Product" margin-right:10px margin-left:10px>
<th mat-header-cell *matHeaderCellDef style="font-size:15px;" class="customtd"><strong>Product</strong></th>
<td mat-cell *matCellDef="let element"> {{element.product}} </td>
</ng-container>
<ng-container matColumnDef="MSAN" margin-right:10px margin-left:10px>
<th mat-header-cell *matHeaderCellDef style="font-size:15px;" class="customtd"><strong>MSAN</strong></th>
<td mat-cell *matCellDef="let element"> {{element.msan}} </td>
</ng-container>
<ng-container matColumnDef="CPE" margin-right:10px margin-left:10px>
<th mat-header-cell *matHeaderCellDef style="font-size:15px;" class="customtd"><strong>CPE</strong></th>
<td mat-cell *matCellDef="let element"> {{element.cpe}} </td>
</ng-container>
<ng-container matColumnDef="Service Connections" margin-right:10px margin-left:10px>
<th mat-header-cell *matHeaderCellDef style="font-size:15px;" class="customtd"><strong>Service Connections</strong></th>
<td mat-cell *matCellDef="let element"> {{element.serviceConnections}} </td>
</ng-container>
<ng-container matColumnDef="License Key" margin-right:10px margin-left:5px>
<th mat-header-cell *matHeaderCellDef style="font-weight: bold;" style="font-size:15px;" class="customtd"><strong>License Key</strong></th>
<td mat-cell *matCellDef="let element"> <textarea rows="2" cols="20" wrap="hard" [readonly]="!editable">{{element.licenseKey}} </textarea></td>
</ng-container>
<ng-container matColumnDef="Actions" margin-right:10px margin-left:10px>
<th mat-header-cell *matHeaderCellDef style="font-weight: bold;" style="font-size:15px;" class="customtd"><strong>Actions</strong></th>
<td mat-cell *matCellDef="let element">
<button type="button" style="margin-left:5px" (click)="deleteLicense(element.id)">Delete</button>
<button type="button" style="margin-left:5px" (click)="openMxkLicenseDetailsDialog()">Update</button>
<button type="button" style="margin-left:5px" (click)="copyLicenseToClipboard(element.licenseKey)" class='btn btn-primary'>Copy License Key</button>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns; sticky:true"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</div>
</mat-dialog-content>
<br>
<br>
<br>
<strong>* Customer ID might not be present for some products.</strong>
<mat-dialog-actions align="end">
<button mat-button mat-raised-button mat-dialog-close cdkFocusInitial color="warn">Close</button>
</mat-dialog-actions>
This page looks like this:
I want to add a search button on top of this popup after the heading. I want to refine this list based on the Customer ID which is of type String. However, the primary key is ID of type long, not shown. ID is #GeneratedValue of property Auto at the backend. I tried the following code but could not implement it properly: https://stackblitz.com/edit/angular-search-filter?file=app%2Fapp.component.ts
The Component.ts file for this is:
#Component({
selector: 'customer-list-dialog',
templateUrl: 'customer-list-dialog.html',
})
export class CustomerListDialog implements OnInit {
customerList : any;
isupdated = false;
displayedColumns: string[] = ['Customer ID', 'Hardware Key', 'Product', 'MSAN', 'CPE', 'Service Connections', 'License Key', 'Actions'];
constructor(
public dialogRef: MatDialogRef<AddProductDialog>,
private generateLicenseService: GeneratelicenseService,
#Inject(MAT_DIALOG_DATA) public data) {
}
ngOnInit() {
console.log("before the call : "+this.customerList);
if(this.customerList === undefined) {
this.generateLicenseService.getCustomerDetails()
.subscribe((data) => {
this.customerList = data;
//console.log("after the call : "+this.customerList);
});
}
}
And the service.ts portion is:
getCustomerDetails() {
let headers = new HttpHeaders({
'Content-Type': 'application/json'
})
let options = {headers:headers, observer: 'response'};
let result : Observable<Object> = this.http.get(this.url+'/customer/licenses',options);
return result;
}
If I'm understanding your question properly, you just want a simple text filter akin to your provided link?
I would suggest the simplest thing to do would be to change the input data source for your table from customerList to filteredCustomerList.
In your component, after receiving your customer list and saving it as customerList, also save it as another variable filteredCustomerList.
With the addition of your newest search input textbox, for example:
<input type="text" [(ngModel)]="filterText" (change)="onFilterChange()">
You can then change the filteredCustomerList contents - leaving the original customerList as the source of the data from which to filter otherwise untouched in the background. For example:
public onFilterChange(): void {
if (!this.filterText || this.filterText.length === 0) {
this.filteredCustomerList = this.customerList;
return;
}
this.filteredCustomerList = this.customerList.filter(x => x.customerId.toString().includes(this.filterText));
}
I suspect that the filter would look something like that, given your concerns about data types (strings vs numeric types). At the end of the day, numbers have (everything has, frankly) a .toString() method available, so that you can compare the entered filter text vs the customer IDs.
This should have the desired effect of changing the input data source based on the entered filter text.
Edit: (change) event is only fired when focus is removed (clicked off the text box) or you hit enter. Switch to (keyup) if you want filtering as you type.
Quick example of the described mechanism working - StackBlitz

Column not showing - mat-table

I am attempting to add row-deletion into my <mat-table>. Most of the table is working fine, except the checkbox column is not showing up. Previously, the code did not contain the <!-- Checkbox/Selection Column --> section. I added it in using one of the examples on angular.material.io.
Im a bit confused, because it looks to me like the pattern should be a <th> & <td> wrapped inside an <ng-container>. I seem to be missing something here, because the checkbox/selection column isn't showing up, there aren't any errors in the browser console, and there aren't any errors being thrown at ng serve in powershell.
<table mat-table [dataSource]="dataSource" matSort>
<!-- Checkbox/Selection Column -->
<ng-container matColumnDef="select">
<th mat-header-cell *matHeaderCellDef>
<mat-checkbox [checked]="false" [aria-label]="checkboxLabel()">
</mat-checkbox>
</th>
<td mat-cell *matCellDef="let row">
<mat-checkbox [checked]="true"></mat-checkbox>
</td>
</ng-container>
<!-- Working Columns -->
<ng-container *ngFor="let field of Fields" matColumnDef="{{field.name}}">
<th class="w-134" mat-header-cell *matHeaderCellDef mat-sort-header>{{field.name}}</th>
<td class="w-130" mat-cell *matCellDef="let row">
<input *ngIf="field.editType == 'free'" matInput [(ngModel)]="row[field.name]" placeholder="{{row[field.name]}}" required>
<mat-select *ngIf="field.editType == 'spinner'" [(ngModel)]="row[field.name]">
<mat-option *ngFor="let option of field.options" [value]="option">{{option}}</mat-option>
</mat-select>
<div class="checkbox-cell" (click)="toggleBoolean(row, field.name)">
<mat-checkbox *ngIf="field.editType == 'checkbox'" [(ngModel)]="row[field.name]" (click)="toggleBoolean(row, field.name)"></mat-checkbox>
</div>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="ColumnHeaders"></tr>
<tr mat-row *matRowDef="let row; columns: ColumnHeaders;"></tr>
</table>
Seems like you did not added the column in your ColumnHeaders array inside TS file.
ColumnHeaders = ['select'] //ColumnHeaders should have an entry of select(your checkbox column defintion)
yes you have to add select inside displayedColumns
displayedColumns: string[] = ['select','position', 'name','gender', 'weight', 'symbol'];