How to do pagination in Angular? - html

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.

Related

Receiving the correct array from the api, but the values ​do not appear in the mat table

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.

Hide Delete User if user is logged AngularJS 8.2.14

Similar to How can I show or hide some buttons depend on the user's rights, in angularjs?, how can I hide Delete button from User list if the user is logged?
user.component.html (ng-hide is not working, is it necessary to change to *ngHide?)
<table mat-table [dataSource]="users" class="mat-elevation-z8">
<ng-container matColumnDef="userId">
<th mat-header-cell *matHeaderCellDef> userId </th>
<td mat-cell *matCellDef="let user"> {{user.userId}} </td>
</ng-container>
<ng-container matColumnDef="accountId">
<th mat-header-cell *matHeaderCellDef> accountId </th>
<td mat-cell *matCellDef="let user"> {{user.account.accountId}} </td>
</ng-container>
<ng-container matColumnDef="accountName">
<th mat-header-cell *matHeaderCellDef> accountName </th>
<td mat-cell *matCellDef="let user"> {{user.account.accountName}} </td>
</ng-container>
<ng-container matColumnDef="userName">
<th mat-header-cell *matHeaderCellDef> userName </th>
<td mat-cell *matCellDef="let user"> {{user.userName}} </td>
</ng-container>
<ng-container matColumnDef="emailAddress">
<th mat-header-cell *matHeaderCellDef> emailAddress </th>
<td mat-cell *matCellDef="let user"> {{user.emailAddress}} </td>
</ng-container>
<ng-container matColumnDef="password">
<th mat-header-cell *matHeaderCellDef> password </th>
<td mat-cell *matCellDef="let user"> {{user.password}} </td>
</ng-container>
<ng-container matColumnDef="enabled">
<th mat-header-cell *matHeaderCellDef> enabled </th>
<td mat-cell *matCellDef="let user"> {{user.enabled}} </td>
</ng-container>
<ng-container matColumnDef="lastLogin">
<th mat-header-cell *matHeaderCellDef> lastLogin </th>
<td mat-cell *matCellDef="let user"> {{user.lastLogin}} </td>
</ng-container>
<ng-container matColumnDef="delete">
<th mat-header-cell *matHeaderCellDef> Action </th>
<td mat-cell *matCellDef="let user"><button ng-hide="user.userName==loginService.getUser()" class="btn btn-danger" (click)="deleteUser(user)"> Delete user</button> </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
user.component.ts
import { Component, OnInit } from '#angular/core';
import { HttpClientService, User} from "../service/httpclient.service";
#Component({
selector: "app-user",
templateUrl: "./user.component.html",
styleUrls: ["./user.component.css"]
})
export class UserComponent implements OnInit {
users: User[];
displayedColumns: string[] = ["userId", "accountId", "accountName", "userName", "emailAddress", "enabled", "lastLogin", "delete"];
constructor(private httpClientService: HttpClientService) {}
ngOnInit() {
this.httpClientService
.getUsers()
.subscribe(response => this.handleSuccessfulResponse(response));
}
handleSuccessfulResponse(response) {
this.users = response;
}
deleteUser(user: User): void {
this.httpClientService.deleteUser(user).subscribe(data => {
this.users = this.users.filter(u => u !== user);
});
}
}
authentication.service.ts
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { map } from 'rxjs/operators';
export class User {
constructor(public status: string) {}
}
#Injectable({
providedIn: 'root'
})
export class AuthenticationService {
constructor(private httpClient: HttpClient) {}
// Provide username and password for authentication, and once authentication is successful,
// store JWT token in session
authenticate(username, password) {
return this.httpClient
.post<any>('http://localhost:9898/authenticate', { username, password })
.pipe(
map(userData => {
sessionStorage.setItem('username', username);
const tokenStr = 'Bearer ' + userData.token;
sessionStorage.setItem('token', tokenStr);
return userData;
})
);
}
isUserLoggedIn() {
const user = sessionStorage.getItem('username');
console.log(!(user === null));
return !(user === null);
}
getUser() {
const user = sessionStorage.getItem('username');
return user;
}
logOut() {
sessionStorage.removeItem('username');
}
}
header.component.html
<mat-toolbar color="primary">
<mat-toolbar-row>
<span><a mat-button href="http://www.conexiona.com" style="font-size: larger;">Conexiona Web Client - Crmiguez</a></span>
<span class="example-fill-remaining-space"></span>
<span class="align-center"></span>
<span class="example-spacer"></span>
<a mat-button *ngIf="!loginService.isUserLoggedIn()" routerLink="/login" class="nav-link">Login</a>
<a mat-button *ngIf="loginService.isUserLoggedIn()" routerLink="/" class="nav-link">View Users</a>
<a mat-button *ngIf="loginService.isUserLoggedIn()" class="nav-link"> Welcome, {{ loginService.getUser() }} !</a>
<a mat-button *ngIf="loginService.isUserLoggedIn()" routerLink="/logout" class="nav-link">LogOut</a>
</mat-toolbar-row>
</mat-toolbar>
Try using *ngIf
<button *ngIf="user.userName==loginService.getUser()" class="btn btn-danger" (click)="deleteUser(user)"> Delete user</button>
The condition seems to be correct, but I recommend you to console log user.userName and loginService.getUser() in order to see if they are actually the same.
I wrote a directive to hide elements, depending on logged in state, and role. This could be modifed:
export class RoleShowDirective implements OnInit, OnDestroy {
private hasView = false;
private roles: string[];
private loggedInSubscription: Subscription;
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef,
private authorizationService: AuthorizationService) { }
#Input() set appRoleShow(roles: string[]) {
this.roles = roles;
// this.evaluate(); //This is not needed as authStatusEvent is emitting on page load
}
ngOnDestroy(): void {
this.loggedInSubscription.unsubscribe();
}
ngOnInit(): void {
this.loggedInSubscription = this.authorizationService.authStatusEvent.subscribe(loggedIn => {
this.evaluate();
});
}
evaluate() {
if (!this.authorizationService.UserLoggedIn) {
this.hide();
return;
}
if (this.authorizationService.UserRole === 'Administrator') {
this.show();
} else if (this.roles && this.roles.indexOf(this.authorizationService.UserRole) !== -1) {
this.show();
} else {
this.hide();
}
}
show() {
this.viewContainer.createEmbeddedView(this.templateRef);
this.hasView = true;
}
hide() {
this.viewContainer.clear();
this.hasView = false;
}
}
The loggedInSubscription is merely an event that my Auth service emits when the user logs in /out
This can be used on any element, by giving it the role it should show for:
<li class="nav-item active" ngbDropdown *appRoleShow="['User']">

Mysql table data is not displaying on Angular material table using Nodejs

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

mat-table won't get filled with data from restservice

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

Paginator not working on multiple table with angular material table

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