Ilan Finkel
Ilan Finkel

Reputation: 496

Angular2 - How to create re-usable component

I have a component with a table and I made my <th></th> tags to be able to sort the data when you click on a th tag the data is being sorted by ASC or DESC

in my component set the click event and the variables:

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();
}

and this is my template HTML

<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>

Because I gonna use this table more than once I would like it to be cleaner and I want it to be more or less like that:

<th>
    <sortable sortBy="name" value="User Name"></sortable>
</th>

I don't know how to create this type of component and how to communicate between components

Upvotes: 0

Views: 55

Answers (2)

Julia Passynkova
Julia Passynkova

Reputation: 17859

You can create a component called header-sortable and use in the parent component as following:

  <header-sortable [name]="'User Name'" [prop]="'name'" 
     [sortBy]="sortBy" (sort)="onSort($event)"></header-sortable>

and here is component skeleton

@Component({
  selector:'header-sortable',
  template: 
  `
   <th (click)="sortTableBy()" style="cursor:pointer;">
    <div>
        <span>{{name}}</span>
        <i *ngIf="sortBy == prop && sort_order == 'desc'" class="fa fa-sort-up"></i>
        <i *ngIf="sortBy == prop && sort_order == 'asc'" class="fa fa-sort-down"></i>
    </div>
</th>
`
})
export class HeaderSortable {
  @Input() sortBy: string;
  @Input() name: string;
  @Input() prop: string;
  @Output() sort = new EventEmitter<any>();

  sortTableBy() {
    let dir;
    if( this.sortBy == this.prop) {
       dir = this.sortBy === 'desc' ? 'asc' : 'desc';
    }
    else {
      dir  = 'desc';
    }
    this.sort.emit({prop, dir})
  }
}

Upvotes: 1

Aravind
Aravind

Reputation: 41543

Simply move the click method to the <th> as below,

<th (click)="sortTableBy('name')" style="cursor:pointer;">
    <div>
        <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>

Note: Added a style so that the user knows he can click on it

Update 1 : 5 <th> tags will also contain the same click method with a input parameter as hard coded in string.

<th (click)="sortTableBy('name')">
<th (click)="sortTableBy('age')">
<th (click)="sortTableBy('gender')">

and so on.

Upvotes: 0

Related Questions