【发布时间】:2020-06-11 16:35:04
【问题描述】:
我正在动态获取字符串列表。我使用 ngFor 以角度显示它。但是在显示时,某些字符串包含很少的超链接,但它们显示为普通字符串。我希望超链接像下划线一样区分。 例如:参考https://support.google.com/accounts/answer/abc?hl=en# 使用电子邮件“创建 Google 帐户”
【问题讨论】:
我正在动态获取字符串列表。我使用 ngFor 以角度显示它。但是在显示时,某些字符串包含很少的超链接,但它们显示为普通字符串。我希望超链接像下划线一样区分。 例如:参考https://support.google.com/accounts/answer/abc?hl=en# 使用电子邮件“创建 Google 帐户”
【问题讨论】:
如果我做对了,它真的很简单,你可以这样做:
<a href="{{yourlinkVariable}}">{{Text Variable}}</a>
【讨论】:
你可以做一个管道,但是这个管道必须在[innerHtml]中使用
@Pipe({name: 'linkPipe'})
export class LinkPipe implements PipeTransform {
constructor(private _domSanitizer: DomSanitizer){}
transform(value: string): any {
if (value.indexOf("http")>=0)
{
//search the "link"
const link=value.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+~#?&//=]*)?(\[.*\])?/)
if (link) //if has a link
{
const valueSplit=link[0].split('[') //check if is in the way:
//http://direccion[text to show]
value=value.replace(link[0],
"<a href='"+valueSplit[0]+"'>"+
(valueSplit[1]?valueSplit[1].slice(0,-1):valueSplit[0])+
"</a>")
}
}
return this._domSanitizer.bypassSecurityTrustHtml(value)
}
}
例如用途
<p [innerHTML]="'see the http://www.google.com[page of Google] for more information'|linkPipe "></p>
<p [innerHTML]="'http://www.google.com'|linkPipe"></p>
【讨论】: