今天主要是
https://www.youtube.com/watch?v=282ITUdC12Y&list=PL9LUW6O9WZqgUMHwDsKQf3prtqVvjGZ6S&index=2
這一集是由 Leo 老師來教學
首先,對Leo老師自己撰寫的文章做導讀,請大家直接看文章,或跟著影片一起看
(YA,終於可以偷懶混過一天了)
Pipe:
https://angular.io/guide/pipes#using-pipes
A pipe takes in data as input and transforms it to a desired output. In this page, you'll use pipes to transform a component's birthday property into a human-friendly date.
在template,對資料,作不同的呈現
選api,再選type=pipe
https://angular.io/api?type=pipe
now = new Date();
https://angular.io/api/common/DatePipe
{{ now | date: 'yyyy/MM/dd HH:mm:ss' }} 2018/12/26 20:40:34
^^變數 ^^pipe ^^^^^^^^^^^^格式
https://angular.io/api/common/CurrencyPipe
{{ value_expression | currency [ : currencyCode [ : display [ : digitsInfo [ : locale ] ] ] ] }}
{{ 1000000 | currency }} $1,000,000.00
一、display,選1種使用,例如:
1. code: Show the code
{{ 1000000 | currency : 'CAD' }} CA$1,000,000.00
^^^ 國幣
2. String: 給 string value 取代 code 或 symbol.
{{ 1000000 | currency : '==' }} =CA1,000,000.00
^^ 把 $ 替換成 ==
二、digitsInfo
{{ 1000000 | currency : '' : '' : '9.1-2' }} =001,000,000.0
^^^
{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
^^^^^^^如果沒限制,0即可 ^^^^^^^^^^^^^^^^^^^小數點1~2位,第3位四捨五入
三、local
配合i18n做多國語言
https://angular.io/guide/i18n#setting-up-the-locale-of-your-app
LOCALE_ID
https://angular.io/guide/i18n#setting-up-locale
Chinese Traditional zh-Hant
https://angular.io/guide/pipes#custom-pipes
import { Pipe, PipeTransform } from '@angular/core';
/*
* Raise the value exponentially
* Takes an exponent argument that defaults to 1.
* Usage:
* value | exponentialStrength:exponent
* Example:
* {{ 2 | exponentialStrength:10 }}
* formats to: 1024
*/
@Pipe({name: 'exponentialStrength'})
export class ExponentialStrengthPipe implements PipeTransform {
transform(value: number, exponent?: number): number {
return Math.pow(value, isNaN(exponent) ? 1 : exponent);
}
}
@NgModule({
declarations: [ ExponentialStrengthPipe ], // pipe放在這裡
imports: [ SharedModule ] // 如果都寫在SharedModule的話,module放在imports
})
export class AppComponent {
now = new Date();
dollar = 1000000;
dates = ['一','二','三','四','五'];
}
<p *ngFor="let date of dates">
今天星期 {{ date }},
我要吃: {{ date | food }}
^^ 把date傳到food pipe的transform(),把pipe的回傳值顯示出來
</p>
@Pipe({name: 'food'})
export class FoodPipe implements PipeTransform {
transform(value: string): string {
^^^只收一個參數 ^^^回傳string
let food = '';
switch(value){
case '一':
food = '滷肉飯';
break;
case '二':
food = '什錦炒麵';
break;
case '三':
food = '麥當勞';
break;
case '四':
food = '雞腿飯';
break;
case '五':
food = '拉麵';
break;
default:
food = '回家吃自己';
break;
}
return food;
}
}