Create Dynamic Data Table In Angular 4
Posted By : Yash Arora | 05-Jun-2018
In this blog, I am going to explain how to generate dynamic drop-down option values and how to show dynamic table data on selecting any of the options from the drop-down list
Let's Start:-
1. Dynamic drop-down options values
As an example, I am taking hard-coded values to explain but you can take values from API response to show data in the drop-down
component.ts file:-
initialize this variable in the class and either this can be the response from API So you can show dynamic option in the drop-down
this.companydepartments =[ {name:"All"},{name:"It"},{name:"HR"},{name:"Infra"},{name:"Finance"} ]
component.html file
<div class="dropdown">
<select id="events" [(ngModel)]= "selectedoption" (ngModelChange)="getDetails($event)" class="form-control">
<option *ngFor="let department of companydepartment" [value]="department.name">{{department.name}}</option>
</select>
</div>
Here companydepartment is same field as initialized in component.ts file
It will create dynamic drop-down option and if we want to select any one as default. Add this lines in component.ts file
this.selectedoption='It' selectedoption is same as mentioned in ngModel in .html file
2.Generate dynamic table data on the selection of particular drop-down option
Add in component.ts file
public DropDownCollector : any;
getDetails(DropDownCollector){
if(DropDownCollector == 'HR'){this.showHrTable()}
if(DropDownCollector == 'It'){this.showItTable()}
}
here getDetails() is the same function as specified in div section in .html file
Now in showHrTable() and showItTable() you can get the response from api and collect the response in some variable like ResponseApi
To explain better i am taking hardcoded values in function
showHrTable(){ this.hrDetails=[{ "EmployeeName":"Diksha", "Department":"HR", "Profile":"Assocaite HR", "Salary":"4.5" }] this.ResposneApi=this.hrDetails;
}
Now to show the table data according to selected drop-down option
component.html file
<table style="width:100%" class="order-history-table">
<thead>
<tr>
<th>EmployeeName</th>
<th>Department</th>
<th>Profile</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let response of ResponseApi ">
<td>{{response.employeeName}}</td>
<td>{{response.department}}</td>
<td>{{response.profile}}</td>
<td>{{response.salary}}</td>
</tbody>
Now it will show dynamic data according to selected option from the drop-down.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Yash Arora