4

Is it possible to change/put pipe to format a specific column in Angular 2 on button click? Like for example I have a table with 'Name' and 'Hours' columns, when I click a button the data displayed for 'Hours' should be converted into days and vice-versa.

<button class="btn btn-secondary" (click)="convertToDays()">Days</button>
<button class="btn btn-secondary" (click)="convertToHours()">Hours</button>

<tbody>
<td>{{availableLeave.hours}}</td>
</tbody>

convertToDays(){
//put pipe to format availableLeave.hours to display as days ex.('48' hours should be displayed as '2' days)
}

convertToHours(){
//will just revert the original formatting of availableLeave.hours which is in hour format
}
xird
  • 775
  • 1
  • 8
  • 16
  • 1
    Please post the code that demonstrates what you try to accomplish. Yes, it's possible, but hard to tell which of the 200 ways would fit your need. – Günter Zöchbauer Feb 13 '17 at 07:02
  • hi Gunter, thanks for checking out, I added some pseudo of what I want to achieve, but seems like someone posted an answer that could help, I'll check which way fits the most. – xird Feb 13 '17 at 10:06

2 Answers2

5

You can pass a parameter to the pipe like

{{someValue | myPipe:param}}

<button class="btn btn-secondary" (click)="param = 'd'">Days</button>
<button class="btn btn-secondary" (click)="param = 'h'">Hours</button>
class MyPipe implements PipeTransform {
  transform(value, param) {
    if(param === 'h') {
      return "...";
    } else {
      return "...";  
    }
  }
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
1

As per your requirement, you can use Pipe directly in your component file. You can make two pipes one for Hours and one for Days then call the transform function of required pipe.

for more details on how to use pipes in component or in service, check this post.

Community
  • 1
  • 1
HirenParekh
  • 3,655
  • 3
  • 24
  • 36