专业的编程技术博客社区

网站首页 > 博客文章 正文

Angular中自定义管道 - 字符串截断

baijin 2024-08-15 16:58:43 博客文章 5 ℃ 0 评论
  1. 使用CLI创建新的管道
ng g p pipes/truncate --skip-tests

truncate.pipe.ts代码如下

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

@Pipe({
  name: 'truncate'
})
export class TruncatePipe implements PipeTransform {

  transform(value: string, maxLength: number, showEllipsis: boolean) {
    const truncatedValue = maxLength ? value.substring(0, maxLength) : value;

    return showEllipsis ? `${truncatedValue}...` : truncatedValue;
  }
}
  1. 创建测试页面
ng g c components/test-pipe --skip-tests

test-pipe.component.html测试代码如下

<p>{{ 'Hello World, I am Taylor.' | truncate:10:true}}</p>

在app-routing.module.ts添加route

{
    path: 'test-pipe',
    component: TestPipeComponent
  }
  1. 在浏览器中测试

输入url

http://localhost:4200/test-pipe

测试结果

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表