I have implemented a feature in my component where a table can be sorted by clicking on the <th></th>
tags. When a user clicks on a th
tag, the data is sorted either in ascending (ASC
) or descending (DESC
) order.
In my component, I have set up the click event and defined the variables as follows:
public sort_by = "name";
public sort_order = "asc";
sortTableBy(sort_by:string){
if(sort_by === this.sort_by){
this.sort_order = (this.sort_order === 'asc' ? 'desc' : 'asc');
}else{
this.sort_order = "asc";
this.sort_by = sort_by;
}
this.updateData();
}
Below is the template HTML code:
<th>
<div (click)="sortTableBy('name')">
<span>User Name</span>
<i *ngIf="sort_by == 'name' && sort_order == 'desc'" class="fa fa-sort-up"></i>
<i *ngIf="sort_by == 'name' && sort_order == 'asc'" class="fa fa-sort-down"></i>
</div>
</th>
Since I plan to use this table sorting functionality multiple times, I would like to abstract it into a reusable component that looks something like this:
<th>
<sortable sortBy="name" value="User Name"></sortable>
</th>
I am not sure how to create such a component and establish communication between components. Any help would be appreciated!