Total Pageviews

2017/01/05

[Angular2] Custom Pipe

Problem
I retrieve a collection of data with json data type, the json structure looks like:


These data will be displayed in data grid:


The second column displays status code, but I would like to display its description instead of code (i.e. 1:使用中、5:已關閉、9:已封存) :


How to do it?

How-To
Utilize custom pipe can solve this problem:

Step1. Create a custom pipe
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'statusPipe' })
export class StatusPipe implements PipeTransform {
  transform(status: number) {
    let statusName = '';
    if (status == 1) {
      statusName = '使用中';
    } else if (status == 5) {
      statusName = '已關閉';
    } else if (status == 9) {
      statusName = '已封存';
    }
    return statusName;
  }
}


Step2. Import custom pipe to your component. Here is the code snippet:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
//...
import { StatusPipe } from './project.pipe';

@Component({
  selector: 'project-list',
  templateUrl: 'project.list.html',
  directives: [MODAL_DIRECTIVES, PAGINATION_DIRECTIVES],
  providers: [ProjectService],
  pipes: [StatusPipe]
})

export class ProjectComponent {

  searchProject: Project = new Project();
  projects: Page<Project>;

  constructor(private projectService: ProjectService, private appNotificationSerivce: AppNotificationService) {
  }
  //...
}  


Step3. Apply pipe to your html page. Here is the code snippet:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
  <div class="well" *ngIf="projects && projects.content.length > 0">
    <div class="table-responsive">
      <table class="table">
        <thead>
          <tr>
            <th width="70%">專案名稱</th>
            <th width="20% ">狀態</th>
            <th width="10% "></th>
          </tr>
        </thead>

        <tbody>
          <tr *ngFor="let project of projects.content; let rowIdx=i ndex ">
            <td> {{ project.name }}</td>
            <td> {{ project.status | statusPipe }}</td>
            <td> </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>



No comments: