Skip to content

6 Pipe

管道的作用是格式化组件模版数据.

6.1 Built in Pipe

  1. date 日期格式化
  2. currency 货币格式化
  3. uppercase 转大写
  4. lowercase 转小写
  5. json 格式化json 数据
{{ date | date: "yyyy-MM-dd" }}

Screenshot 2025-01-17 at 17.47.28

import { Component } from '@angular/core';


// 组件类 被@Component装饰器装饰
@Component({

  // 制定组件的使用方式, 当前问标记形式
  // app-root => <app-root></app-root> 

  selector: 'app-root', // 当前组件调用的时候你要以什么形式去调用
  templateUrl: './app.component.html', // 当前组件对应的模版是什么 组件模版文件路径
  styleUrls: ['./app.component.css'] // 当前组件对应的样式文件
})

// 导出一个类 
export class AppComponent {
  date = new Date();
}

// selector: '.app-root', // 当前组件调用的时候你要以什么形式去调用
// app-root => <div class="app-root"></div>
// selector: '[app-root]', // 当前组件调用的时候你要以什么形式去调用
// app-root => <div app-root></div>
<div> {{ date }} </div>

Screenshot 2025-01-17 at 17.47.57

Screenshot 2025-01-17 at 17.48.38

Screenshot 2025-01-17 at 17.48.44

需要给管道传参

Screenshot 2025-01-17 at 23.46.24

Screenshot 2025-01-17 at 23.46.34

Screenshot 2025-01-17 at 23.48.11

Screenshot 2025-01-17 at 23.48.17

Screenshot 2025-01-18 at 00.14.33

Screenshot 2025-01-18 at 00.14.42

Screenshot 2025-01-18 at 00.15.37

Screenshot 2025-01-18 at 00.15.43

6.2 Custom Pipes

需求: 指定字符串不能超过规定的长度

ng g p components/pipe/custom/custom

Screenshot 2025-02-05 at 13.20.44

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'custom'
})
export class CustomPipe implements PipeTransform {

  transform(value: string, ...args: number[]): string {
    console.log(value);
    console.log(args);

    return "test";
  }

}
<div> {{ money | currency: "$" }}</div>


<div> {{ test | json }} </div>
<div>
    <pre>{{ test | json }}</pre>
</div>

<p>custom pipe</p>
<div>{{paragraph }}</div>
<div>{{ paragraph | custom }}</div>

<div>{{ paragraph | custom: 100 : 200}}</div>

Screenshot 2025-02-05 at 13.39.31

Screenshot 2025-02-05 at 13.39.40

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'custom'
})
export class CustomPipe implements PipeTransform {

  transform(value: string, limit?: number): string {
    return value.substr(0, limit || 10) + "...";

  }

}
<p>pipe works!</p>
<p> These are angular built-in pipes </p>
<div> {{ date }} </div>

<div> {{ date | date: "yyyy-MM-dd" }} </div>

<div> {{ money | currency: "$" }}</div>


<div> {{ test | json }} </div>
<div>
    <pre>{{ test | json }}</pre>
</div>

<p>custom pipe</p>
<div>{{paragraph }}</div>
<div>{{ paragraph | custom }}</div>

<div>{{ paragraph | custom: 20}}</div>

Screenshot 2025-02-05 at 13.42.31

Screenshot 2025-02-05 at 13.42.37