I have few table in my application with mat-paginator. The first table paginator(#paginatorregin) working fine.The second table paginator(#paginatorcountry) and sorting is not working but length applied on pagination table based on how much value i got from json object, here i add my code below
<table mat-table [dataSource]="regionsDataSource" matSort>
<ng-container matColumnDef="regions">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Regions</th>
<td mat-cell *matCellDef="let element"> {{element.regions}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="regionsColumn"></tr>
<tr mat-row *matRowDef="let row; columns: regionsColumn;"></tr>
</table>
<mat-paginator #paginatorregin [length]="regionsDataSource.length" [pageSize]="3" [pageIndex]="0" [pageSizeOptions]="[3,5,10]"showFirstLastButtons></mat-paginator>
<table mat-table [dataSource]="countryDataSource" matSort>
<ng-container matColumnDef="country">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Contry</th>
<td mat-cell *matCellDef="let element"> {{element.name}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="countryColumn"></tr>
<tr mat-row *matRowDef="let row; columns: countryColumn;"></tr>
</table>
<mat-paginator #paginatorcountry [length]="countryDataSource.length" [pageSize]="10" [pageIndex]="0"[pageSizeOptions]="[10, 20, 40]" showFirstLastButtons> </mat-paginator>
<mat-form-field>
<mat-select placeholder="Regions" [(ngModel)]="adminsettingvalue.reginvalue" (ngModelChange)="regionChangeItem($event)"
name="regindropdown">
<mat-option *ngFor="let region of regiondropdown" [value]="region.id">
{{region.viewValue}}
</mat-option>
</mat-select>
component code:
export interface Regions {
regions: string;
}
const regionElememtData: Regions[] = [
{ regions: 'Americas' },
{ regions: 'Asia Pacific' },
{ regions: 'Europe' },
{ regions: 'Middle East' },
{ regions: 'Africa' }
];
const countryDataSource = [];
#ViewChild('paginatorregin') paginator: MatPaginator;
#ViewChild('paginatorcountry') paginatorcountry: MatPaginator; #ViewChild(MatSort) sort: MatSort;
regionsColumn: string[] = ['regions'];
countryColumn: string[] = ['country'];
regionsDataSource = new MatTableDataSource<Regions>(regionElememtData);
countryDataSources = new MatTableDataSource(countryDataSource);
ngOnInit() {
this.regionsDataSource.paginator = this.paginator;
this.regionsDataSource.sort = this.sort;
}
ngAfterViewInit() {
this.countryDataSource.paginator = this.paginatorcountry;
this.countryDataSource.sort = this.sort;
}
listOfCounty: any = [];
countryDataSources = new MatTableDataSource();
regionChangeItem(eventvalue) {
if (eventvalue == 1) {
this.commonservice.getAmericaList().subscribe(americavalue => {
this.listOfCounty= americavalue;
})
}
this.countryDataSources.data = this.listOfCounty;
}
Here the first table working as expected with sort, pagination. Second table pagination value applied with json value length but it will display total value i add 10 data per page it's working the #paginatorcounty table.
You can try by using two matSort selectors for two different table like:
HTML Code:
// For table 1
<table mat-table [dataSource]="regionsDataSource" #t1Sort="matSort" matSort>
// Tr and other table related content
</table>
// For table 2
<table mat-table [dataSource]="countryDataSource" #t2Sort="matSort" matSort>
// Tr and other table related content
</table>
In TS:
#ViewChild('paginatorregin') paginator: MatPaginator;
#ViewChild('paginatorcountry') paginatorcountry: MatPaginator;
#ViewChild('t1Sort') t1Sort: MatSort; // use two diff. sort for two table
#ViewChild('t2Sort') t2Sort: MatSort;
regionsColumn: string[] = ['regions'];
countryColumn: string[] = ['country'];
regionsDataSource = new MatTableDataSource<Regions>(regionElememtData);
countryDataSource = new MatTableDataSource<Country>(countryElememtData);
constructor() {}
ngOnInit() {
this.regionsDataSource.paginator = this.paginator;
this.regionsDataSource.sort = this.t1Sort;
this.countryDataSource.paginator = this.paginatorcountry;
this.countryDataSource.sort = this.t2Sort;
}
EDIT:
if (eventvalue == 1) {
this.commonservice.getAmericaList().subscribe(americavalue => {
this.listOfCounty= americavalue;
this.countryDataSources.data = this.listOfCounty;
this.countryDataSource.paginator = this.paginatorcountry; // Add these two lines here
this.countryDataSource.sort = this.t2Sort;
})
}
WORKING DEMO
Related
I am attempting to display values as follows:
Asteroid Number
Selected Value
1566
some value
1842
some value
etc.
some value
Here are the HTML and TypeScript:
TypeScript
import { Asteroid } from '../models/asteroid.model';
import { DataSource } from "#angular/cdk/collections";
import { MatTableDataSource } from '#angular/material/table';
import { BehaviorSubject, Observable } from 'rxjs';
import { AsteroidService } from '../_services/asteroid.service';
import { AsteroidCharacteristics } from '../enums/characteristic.enum';
import { FormControl } from '#angular/forms';
#Component({
selector: 'app-asteroid-details',
templateUrl: './asteroid-details.component.html',
styleUrls: ['./asteroid-details.component.scss']
})
export class AsteroidDetailsComponent implements OnInit {
dataSource = new AsteroidDataSource(this.asteroidService);
optionsForm: FormControl = new FormControl();
displayedColumns: string[] = ["name", "characteristics"];
charOptions: string[] = [
AsteroidCharacteristics.semimajor_axis,
AsteroidCharacteristics.eccentricity,
AsteroidCharacteristics.perihelion_distance,
AsteroidCharacteristics.perihelion_date,
AsteroidCharacteristics.aphelion_distance,
AsteroidCharacteristics.aphelion_date,
AsteroidCharacteristics.delta_v,
AsteroidCharacteristics.diameter,
AsteroidCharacteristics.price,
AsteroidCharacteristics.mass
];
constructor(private readonly asteroidService: AsteroidService) { }
ngOnInit(): void {
}
}
export class AsteroidDataSource extends DataSource<any> {
data = new BehaviorSubject<Array<Asteroid>>(undefined);
variable = getSelection();
constructor(private readonly asteroidService: AsteroidService) {
super();
asteroidService.asteroidData.subscribe(res => this.data.next(res));
}
connect(): Observable<Array<Asteroid>> {
console.log("data:" + this.data);
return this.data;
}
disconnect() {}
getSelection(value){
if (value == "Semimajor Axis"){
var select = "semimajor";
}
else if (value == "Eccentricity"){
var select = "eccentricity";
}
else if (value == "Perihelion Distance"){
var select = "perihelion_distance";
}
else if (value == "Perihelion Date"){
var select = "perihelion_date";
}
else if (value == "Aphelion Distance"){
var select = "aphelion_distance";
}
else if (value == "Aphelion Date"){
var select = "aphelion_date";
}
else if (value == "Velocity"){
var select = "delta_v";
}
else if (value == "Diameter"){
var select = "diameter";
}
else if (value == "Price"){
var select = "price";
}
else if (value == "Mass"){
var select = "mass";
}
return select;
};
}
HTML
<p>asteroid-details table</p>
<!-- <table mat-table #table [dataSource]="asteroidDetailsList" class="mat-elevation-z8" matSort>
</table> -->
<table mat-table [dataSource] = "dataSource">
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef>Asteroid Name </th>
<td mat-cell *matCellDef="let asteroid"> {{ asteroid.number }} </td>
</ng-container>
<ng-container matColumnDef="characteristics">
<th mat-header-cell *matHeaderCellDef>
<mat-form-field appearance="fill">
<mat-select placeholder="Characteristic"[formControl]="optionsForm">
<mat-option>None</mat-option>
<mat-option *ngFor="let char of charOptions" [value]="char">{{ char }}</mat-option>
</mat-select>
</mat-form-field>
</th>
<td mat-cell *matCellDef="let asteroid"> {{ asteroid.variable }} </td>
</ng-container>
<!-- <ng-container *ngFor="optionsForm.value === 'Mass'">
<tr mat-row *ngFor="let asteroid of asteroidData">asteroid.mass</tr>
</ng-container> -->
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
More specifically, how can I assign a value from the selection to the table? If I manually enter a value (asteroid.eccentricity or asteroid.semimajor_axis) it correctly displays the values.
Many thanks!
I decided to learn angular a few weeks ago, but I have difficulties. I can't populate a table with values received from an API using MatTable .
I am receiving the correct values from the api but these values do not appear in the table, no errors while compiling.
I've tried many solutions but none of them worked. Please help
HTML:
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container matColumnDef="ID">
<th mat-header-cell *matHeaderCellDef> ID </th>
<td mat-cell *matCellDef="let element"> {{element.ID}} </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="animaltype">
<th mat-header-cell *matHeaderCellDef> AnimalType </th>
<td mat-cell *matCellDef="let element"> {{element.animaltype}} </td>
</ng-container>
<ng-container matColumnDef="race">
<th mat-header-cell *matHeaderCellDef> Race </th>
<td mat-cell *matCellDef="let element"> {{element.race}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
Typescript:
import { AfterViewInit, Component, ViewChild, OnInit } from '#angular/core';
import { MatTableDataSource } from '#angular/material/table';
import { User } from 'src/app/models/user.model';
import { Adoption } from 'src/app/models/adoption.model';
import { AccountService } from '../services/account.service';
#Component({
selector: 'app-myadoptions',
templateUrl: './myadoptions.component.html',
styleUrls: ['./myadoptions.component.css']
})
export class MyadoptionsComponent implements OnInit {
allAdoption: Adoption[];
dataSource: MatTableDataSource<Adoption>;
displayedColumns: string[] = ['ID', 'name', 'animaltype', 'race'];
user: User;
string: string;
payload;
constructor(private accountService: AccountService) {
}
ngOnInit() {
this.adoptions();
}
public adoptions() {
let resp = this.accountService.getAdoptions(this.getUserId());
resp.subscribe(data => {
this.dataSource = new MatTableDataSource(data);
console.log(this.dataSource.data);
});
}
getUserId() {
this.string = localStorage.getItem('user');
this.user = (JSON.parse(this.string));
if (this.user.token) {
this.payload = this.user.token.split(".")[1];
this.payload = window.atob(this.payload);
const userString = JSON.parse(this.payload);
return parseInt(userString.UserID);
}
}
}
Model:
export class Adoption {
id: number;
name: string;
animaltype: string;
race: string;
UserID: number;
text: string;
adopted: boolean;
}
Console log:
Console.log
Table:
table
I suspect that the response from getAdoptions has the data you are looking for in a nested property named data, but what you are loading into the MatTable is the outer response object itself.
i.e., you are doing:
let resp = this.accountService.getAdoptions(this.getUserId());
resp.subscribe(data => {
this.dataSource = new MatTableDataSource(data);
which looks reasonable, but when I look at your console output for this.dataSource.data, I see that the Adoption records are in a property named data. i.e., the original shape of the returned information is probably:
getAdoptionsResponse: {
data: Adoption[];
}
If this is the case, you need to update your code to do:
let resp = this.accountService.getAdoptions(this.getUserId());
resp.subscribe(response => {
this.dataSource = new MatTableDataSource(response.data);
in order to load the data correctly.
You should be able to verify this (or refute it) by printing out the value you get from the getAdoptions subscription.
I'm getting the data from the back-end using the getUsers API, and then displaying the values using mat table. I'm trying to add the paginator only for the front-end but this does not work. Do I need to add a paginator logic in the allUsers API as well? Please help me edit my code below to enable pagination.
allUsers API
public List<User> allUserss() {
Query q = entityManager.createQuery("SELECT u FROM User u");
return (List<User>) q.getResultList();
}
typescript
export class GadgetSearchFormComponent implements OnInit {
users:any;
user:User= new User(0,"","","");
firstName:string;
lastName:string;
gender:string;
ELEMENT_DATA: User[];
displayedColumns: string[]=['firstName' ,'dob' ,'gender',];
datasource;
filterForm: FormGroup;
constructor(private service: GadgetTracerLogService, private route:ActivatedRoute, private router:Router, private fb:FormBuilder,private dialog: MatDialog) {
this.filterForm = this.fb.group({
firstName: [''],
lastName: [''],
gender: ['']
});
}
#ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
ngOnInit() {
this.datasource=new MatTableDataSource<User>(this.ELEMENT_DATA);
this.filterForm.get("firstName").setValue(null);
this.filterForm.get("lastName").setValue(null);
this.filterForm.get("gender").setValue(null);
this.getUsers();
}
public getUsers(){
let resp=this.service.getUsers();
resp.subscribe(report=>this.datasource=report as User[]);
}
}
html
<mat-card class="data-card">
<mat-card-content>
<table id="DataPreview" mat-table [dataSource]="datasource" multiTemplateDataRows class="mat-elevation-z8" width="100%">
<ng-container matColumnDef="firstName">
<th mat-header-cell *matHeaderCellDef> Full Name </th>
<td mat-cell *matCellDef="let element"> {{element.firstName}} {{element.lastName}} </td>
</ng-container>
<!-- Name Column -->
<ng-container matColumnDef="lastName">
<th mat-header-cell *matHeaderCellDef> Last Name </th>
<td mat-cell *matCellDef="let element"> {{element.lastName}} </td>
</ng-container>
<!-- Symbol Column -->
<ng-container matColumnDef="gender">
<th mat-header-cell *matHeaderCellDef> Gender </th>
<td mat-cell *matCellDef="let element"> {{element.gender}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;" (click)="updateSymptomCodeConfigDialog(row)"></tr>
<mat-error *ngIf="searchResultMessage">{{searchResultMessage}}</mat-error>
</table>
<mat-paginator #paginator [pageSize]="5" [pageSizeOptions]="[5, 10, 25, 50]">
</mat-paginator>
</mat-card-content>
</mat-card>
in subscribe you create the dataSource and asign the pagination, but remember, you need create a MatTableDataSource
resp.subscribe(report=>{
//see that teh dataSource is a "MatTableDataSource", not the array
this.datasource=new MatTableDataSource<User>(report);
this.dataSource.paginator = this.paginator;
});
You are not connecting your paginator with your data source
Replace this with your viewChild in TS
#ViewChild('paginator') paginator: MatPaginator;
After initializing dataSource in ngOnInIt you have to connect dataSource with your paginator reference like :
ngOnInit() {
this.datasource=new MatTableDataSource<User>(this.ELEMENT_DATA);
this.datasource.paginator = this.paginator;
}
Just do these changes and if any doubt feel free to ask me.
HTML file
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container matColumnDef="id">
<th mat-header-cell *matHeaderCellDef> No. </th>
<td mat-cell *matCellDef="let element"> {{element.id}} </td>
</ng-container>
<ng-container matColumnDef="stud_id">
<th mat-header-cell *matHeaderCellDef> Stud_id </th>
<td mat-cell *matCellDef="let element"> {{element.stud_id}} </td>
</ng-container>
<ng-container matColumnDef="stud_app_date">
<th mat-header-cell *matHeaderCellDef> Date </th>
<td mat-cell *matCellDef="let element"> {{element.stud_app_date | date}} </td>
</ng-container>
<ng-container matColumnDef="stud_first_name">
<th mat-header-cell *matHeaderCellDef> Name </th>
<td mat-cell *matCellDef="let element"> {{element.stud_first_name}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
**component file**
import { Component, OnInit } from '#angular/core';
import { MatTableDataSource } from '#angular/material/table';
import {student} from '../_interface/stud.model';
import { RegistrationService } from '../../../registration.service';
#Component({
selector: 'app-get-stud',
templateUrl: './get-stud.component.html',
styleUrls: ['./get-stud.component.css']
})
export class GetStudComponent implements OnInit {
public displayedColumns = ['id', 'stud_id', 'stud_app_date','stud_first_name'];
public dataSource = new MatTableDataSource<student>();
constructor(private _registrationService : RegistrationService) { }
ngOnInit() : void {
this.getAllStudents();
}
public getAllStudents = () => {
this._registrationService.registerGetStud()
.subscribe(res => {
this.dataSource.data = res as student[],
response => console.log('Success!',response),
error => console.error('Error!',error);
console.log(this.dataSource.data);
})
}
}
**interface**
export interface student{
id: number;
stud_id: string;
stud_app_date: Date;
stud_first_name: string;
}
Unchecked runtime.lastError: The message port closed before a response was received.
I would have to display the mysql table data in angular material table using node js api.. but it is not displaying any data...
Then i checked the node js api using postman and even i checked the console log.. but data's are displaying on both...
Try this by adding change detector to render changes
first, u need to inject it in the constructor
constructor(private readonly changeDetectorRef: ChangeDetectorRef, private _registrationService : RegistrationService)
Then u need to add markforcheck after data added like below
public getAllStudents = () => {
this._registrationService.registerGetStud()
.subscribe(res => {
this.dataSource.data = res as student[]
this.changeDetectorRef.markForCheck();
})
}
component file
public getAllStudents = () => {
this._registrationService.registerGetStud()
.subscribe(res => {
console.log(res),
this.dataSource.data = res.response as student[],
response => console.log('Success!',response),
error => console.error('Error!',error);
console.log(this.dataSource.data);
})
}
Actually, i am sending the result in response(in node js)...so, added the response in component file along with added the data in html file...now its working fine...like
this.dataSource.data = res.response as student[],
{"status":200,"response":[{"id":1,"stud_id":"STUDENT_ID_0",".......
html
<table mat-table [dataSource]="dataSource.data".....
Thank you so much Atresh Kulkarni for your concern
I am getting an array from my restservice. This is working and some information of the response I am printing on the page. But strangely I cannot fill my mat-table and I don't know why.The mat-table was working before, I am just not putting the data in it the right way. Every help will be appreciated.
table-paginator-component.ts:
import {Component, OnInit, ViewChild} from '#angular/core';
import {MatPaginator} from '#angular/material/paginator';
import {MatTableDataSource} from '#angular/material/table';
import {HttpService} from '../http.service';
import { HttpClient } from '#angular/common/http';
import {AreaCode} from '../models/areacode';
#Component({
// tslint:disable-next-line: component-selector
selector: 'table-paginator',
styleUrls: ['table-paginator.component.css'],
templateUrl: 'table-paginator.component.html',
})
export class TablePaginatorComponent implements OnInit {
displayedColumns: string[] = ['standort', 'stammnummer', 'bereich'];
products = [];
dataSource = new MatTableDataSource<any>(this.products);
constructor(private httpClient: HttpClient) {
this.getAreaCodes();
}
#ViewChild(MatPaginator, {static: true}) paginator: MatPaginator;
ngOnInit() {
this.dataSource.paginator = this.paginator;
}
getAreaCodes() {
this.httpClient.get('http://localhost:8080/phonenumbersmanagement/api/v1/areacodes/all')
.subscribe((res:
any[]) => {
console.log(res);
this.products = res;
});
}
}
table-paginator.component.html:
<!-- <button (click)="getAreaCodes2()">GET /productss</button> -->
<ul>
<li *ngFor="let product of products" >
-- id: {{product.id}}
-- name: {{product.title}}
-- base: {{product.base}}
</li>
</ul>
<div class="mat-elevation-z8">
<table mat-table [dataSource]="dataSource">
<!-- Position Column -->
<ng-container matColumnDef="standort">
<th mat-header-cell *matHeaderCellDef> Standort </th>
<td mat-cell *matCellDef="let element"> {{element.title}} </td>
</ng-container>
<!-- Name Column -->
<ng-container matColumnDef="stammnummer">
<th mat-header-cell *matHeaderCellDef> Stammnummer </th>
<td mat-cell *matCellDef="let element"> {{element.title}} </td>
</ng-container>
<!-- Weight Column -->
<ng-container matColumnDef="bereich">
<th mat-header-cell *matHeaderCellDef> Bereich </th>
<td mat-cell *matCellDef="let element"> {{element.title}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<mat-paginator [pageSizeOptions]="[5, 10, 20]" showFirstLastButtons></mat-paginator>
</div>
Current Output:
try with this.products = res;
this.datasource.data = res;
Change your getAreaCodes method like below,
getAreaCodes() {
this.httpClient.get('http://localhost:8080/phonenumbersmanagement/api/v1/areacodes/all')
.subscribe((res: any[]) => {
this.products = res;
this.dataSource = new MatTableDataSource(res);
});
}
Update your mat-paginator with length as like property binding.
<mat-paginator [length]="products.length" [pageSizeOptions]="[5, 10, 20]" showFirstLastButtons></mat-paginator>
I think that, when you receive data from api and add result value to products variable then datasource variable dont update.
Try to use products variable on html table tag-> [dataSource]="products"
This thing worked for me. import table from angular/material and create an
instance of it using viewchild. get your user data and set displayedColumns in ngOnInit(), In ngAfterContentChecked() you need to create MatTableDataSource instance and set this instance to table.dataSource in ngAfterViewInit() check below
import { MatTable, MatTableDataSource } from '#angular/material/table';
export class GetUserComponent implements OnInit {
#ViewChild(MatTable, {static:false}) table: MatTable<any>;
dataSource :any;
constructor(private appService:AppService){}
ngOnInit() {
this.appService.getUsers().subscribe(data => {
this.userData= data;
});
this.displayedColumns = ['select','title','content'];
}
ngAfterViewInit() {
this.table.dataSource = this.dataSource;
}
ngAfterContentChecked(){
this.dataSource = new MatTableDataSource (this.userData);
}
}
you can check my stackblitz here
https://stackblitz.com/edit/angular-dynamicexamples