这是我在 ionic5 中使用 Angular 的一种方法:创建一个过滤器(管道)。这个只会尝试查找 URL 并缩短长的,但它也可以很容易地扩展到查找长的单词。
您的过滤器管道(prep-text-pipe.pipe)
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'prepText'
})
export class PrepTextPipe implements PipeTransform {
transform(textInput: string): any {
if (textInput.trim()=="") {
return;
}
// this is just going to find long URLs, surround them with <a href's and shorten them
let urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
return text.replace(urlRegex, function(url) {
if (url.length > 10) {
if (url.indexOf("://")!==-1) short_url =url.split("://")[1].substr(0,8) + "..." ;
else short_url =url.substr(0,8) + "..." ;
} else short_url = url;
return '<a href="' + url + '" target="_blank">' + short_url + '</a>';
});
}
}
你的 component.ts
import { PrepTextPipe } from '../shared/pipes/prep-text-pipe.pipe';
您的 component.html 请注意,因为我们要返回 HTML,所以我使用的是[innerHTML]
而不是{{}}
<ion-item class="ion-text-wrap" [innerHTML]="myText | prepText">
</ion-item>