在Angular中截断一个文本内容的多种方法

348 阅读2分钟

有时,长的内容字符串文本需要用有限的字符截断并显示在Angular应用程序中。

我们有多种方法可以做到

  • Angular slice pipe来截断字符串内容
  • 添加椭圆并截断字符串。

这个例子确实限制了UI上显示的字符数。

Typecript组件:声明了一个容纳长内容的变量内容。

import { Component, OnInit } from '@angular/core';
import { DecimalPipe } from '@angular/common';

@Component({
  selector: 'app-component',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  constructor() { }
  content: string = "long form of text display"
  ngOnInit(): void {
  }

}

Angular提供了内置的slice管道

它创建了一个字符串数组的子部分。

它需要开始和结束参数。

{{expression|slice :start[:end]}}

expression是一个变量或Angular javascript表达式。start是一个索引起始位置。end是一个结束索引起始位置。对于一个字符串,要截断到10个字符。

{{variable|slice: 0,10 }}

这里是一个Angular html组件。

Angular truncate text example

    {{content| slice:0:10}}

如果你想在截断字符串内容后添加一个椭圆或一些字符串。

这里有一个组件的例子

Angular trucate text & add some string example

    {{ (content.length>10)? (content | slice:0:10)+'>>>':(content) }}

Angular CSS组件用于限制长文本并在末端添加椭圆。

我们也可以在Angular组件中使用CSS来限制长文本。

下面是一个例子


This is long textThis is long textThis is long textThis is long textThis is long textThis is long
        textThis is long textThis is long textThis is long textThis is long textThis is long textThis is long textThis
        is long textThis is long textThis is long textThis is long textThis is long textThis is long textThis is long
        textThis is long textThis is long textThis is long textThis is long textThis is long textThis is long textThis
        is long textThis is long textThis is long textThis is long textThis is long textThis is long textThis is long
        textThis is long textThis is long textThis is long textThis is long textThis is long textThis is long textThis
        is long textThis is long textThis is long textThis is long textThis is long textThis is long textThis is long
        textThis is long textThis is long textThis is long textThis is long textThis is long textThis is long textThis
        is long textThis is long textThis is long textThis is long textThis is long textThis is long textThis is long
        textThis is long textThis is long textThis is long textThis is long textThis is long textThis is long textThis
        is long textThis is long textThis is long textThis is long textThis is long textThis is long textThis is long
        textThis is long textThis is long textThis is long textThis is long textThis is long textThis is long textThis
        is long textThis is long textThis is long textThis is long textThis is long textThis is long textThis is long
        textThis is long textThis is long textThis is long textThis is long textThis is long textThis is long textThis
        is long textThis is long textThis is long text.

这里是一个CSS代码

.text {
    display: -webkit-box;
    max-width: 300px;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    overflow: hidden;
}