角度,使评论中的链接可点击



我正在开发一个应用程序,用户可以在其中向某些字段添加注释。这些评论也可以是链接。因此,作为一个用户,我希望能够点击这些链接,而不是复制粘贴到一个新的标签

  • 如果注释/属性值中出现正常的web链接([http://|http:]…或[https://|https:]…(,则应将其显示为可单击的链接
  • 多个链接可能出现在同一注释/属性值中
  • 单击链接将打开一个新的浏览器选项卡,该选项卡将调用此链接

这就是表单控件的管理方式。我想我可以在regex的帮助下识别多个链接,但如何使它们也可点击?

感谢您的提前回答和帮助。

this.formControl = new FormControl('', [this.params.customValidations(this.params)]);
this.formControl.valueChanges.subscribe(() => {
this.sendStatusToServices();
}); 

在表单编辑器/输入之外(很可能是您想要的(

在将表单字段的值保存到数据库之前,或者在向用户显示之前编辑从数据库接收的正文之前,可以使用Regex将链接替换为锚标记。

function replaceURLWithHTMLLinks(text) {
var exp = /(b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|])/ig;
return text.replace(exp,"<a href='$1'>$1</a>"); 
}

富文本编辑器

然而,如果你试图在表单输入中启用链接(比如WordPress的文本编辑器(,那就有点困难了。您需要一个<textarea>来启用自定义HTML元素。然后,您需要检测用户何时键入了URL,以便调用replaceURLWithHTMLLinks()。老实说,你应该用一个包裹。外面有好几个。

  • Angular Rich Text Editor-所见即所得标记编辑器,由SyncFusion提供
  • NgxEditor,作者:sibiraj-s
  • 打字编辑器

希望这能帮助

使用regex方法和管道,我能够想出如下的东西。我正在做的是使用一个合适的regex将链接替换为超链接标记。

url替换正则表达式取自此处

支持同一评论中的多个链接。

这是管道代码的样本

@Pipe({
name: 'comment'
})
export class CommentPipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer){}
transform(value: any, args?: any): any {
const replacedValue = this.linkify(value);
return this.sanitizer.bypassSecurityTrustHtml(replacedValue)
}
// https://stackoverflow.com/questions/37684/how-to-replace-plain-urls-with-links#21925491
// this method is taken from above answer
linkify(inputText: string) {
var replacedText, replacePattern1, replacePattern2, replacePattern3;
//URLs starting with http://, https://, or ftp://
replacePattern1 = /(b(https?|ftp)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|])/gim;
replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
//URLs starting with "www." (without // before it, or it'd re-link the ones done above).
replacePattern2 = /(^|[^/])(www.[S]+(b|$))/gim;
replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
//Change email addresses to mailto:: links.
replacePattern3 = /(([a-zA-Z0-9-_.])+@[a-zA-Z_]+?(.[a-zA-Z]{2,6})+)/gim;
replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
return replacedText;
}
}

这是完整的堆叠式

如果你想要输入本身的链接,你可能想尝试不同的方法

最新更新