Reputation: 51
I am displaying a message on my angular app using interpolation. The message include name of a person too. I am using @ to specify the person name. what i want is where ever any persons name come in message which i am displaying it should be a hyper link. when click to the link person gets redirected to the person profile.
Upvotes: 3
Views: 352
Reputation: 5935
You want to build a pipe directive
It turns out that manipulating DOM elements is much better suited for directives and components.
Here is my working StackBlitz directive.
Regular Expression Method
I got help to find the regex /@[0-9a-zA-Z]{5,20}(?=\\s|$)/
that works:
// REGEX-MATCH AND REPLACE THE USERNAME SUBSTRING(S)
ngAfterViewInit(){
this.initialText = this.el.nativeElement.innerText;
this.finalText = this.initialText.replace(/@[0-9a-zA-Z]{5,20}(?=\\s|$)/, function(username) {
return `<a href="#${username.substring(1)}">${username}</a>`;
});
Looping Method
When looping you must test every word to check for multiple occurrences of @xxxxxxx
usernames.
Both versions are in the StackBlitz with working innerHTML
replacement.
ngAfterViewInit(){
this.initialText = this.el.nativeElement.innerText;
if (this.initialText && this.initialText.length > 0) {
for (let text of this.initialText.split(" ")) {
if (text.startsWith("@") && text.length > 1){
this.finalText += `<a href="#${text.substring(1)}">${text}</a> `;
} else {
this.finalText += text + " ";
}
}
}
}
Upvotes: 2