5 Angular-管道(自定義)

1 代碼結構

 

 2 myc02.component.ts

 1 import { Component, OnInit } from '@angular/core';
 2 
 3 @Component({
 4   selector: 'app-myc02',
 5   templateUrl: './myc02.component.html',
 6   styleUrls: ['./myc02.component.css']
 7 })
 8 export class Myc02Component implements OnInit {
 9 
10   emps = [
11     { name: '劉備', age: 37, sex: 1 },
12     { name: '孫尚香', age: 18, sex: 0 },
13     { name: '呂布', age: 31, sex: 1 },
14     { name: '貂蟬', age: 19, sex: 0 },
15   ];
16   constructor() { }
17 
18   ngOnInit(): void {
19   }
20 
21 }
myc02.component.ts

3 gender.pipe.ts

 1 import { Pipe, PipeTransform } from '@angular/core';
 2 
 3 @Pipe({
 4   name: 'gender'
 5 })
 6 export class GenderPipe implements PipeTransform {
 7   // {{item.sex|gender:'xxx'}}
 8   //固定的管道寫法{{value|管道名}}
 9   // value就會固定的傳遞到下方transform方法的參數1中,
10   transform(value: any, lang = 'zh') {
11     console.log(value);
12     if (lang == 'en') {
13       if (value == 0) return 'Female';
14       else return 'Male';
15     } else {
16       if (value == 0) return '女';
17       else return '男';
18     }
19   }
20 }
gender.pipe.ts

4 myc02.component.html

 1 <p>myc02 works!</p>
 2 
 3 <!--自定義管道 pipe-->
 4 <table border="1">
 5     <tr>
 6         <td>序號</td>
 7         <td>姓名</td>
 8         <td>年齡</td>
 9         <td>性別</td>
10         <td>性別(EN)</td>
11     </tr>
12     <tr *ngFor="let item of emps; let i=index">
13         <td>{{i+1}}</td>
14         <td>{{item.name}}</td>
15         <td>{{item.age}}</td>
16         <!--製作gender管道
17         生成自定義管道的命令:ng g p 管道名
18         例如:ng g p gender-->
19         <td>{{item.sex|gender}}</td>
20         <td>{{item.sex|gender:"en"}}</td>
21     </tr>
22 </table>
myc02.component.html

5 效果圖

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章