routerLink doesn't work when generated via pipes

1k views Asked by At

I'm trying to write a pipe that can make any words with #hashtaginto a url exactly like twitter.

This is the function in my pipes that generates converts #tags into urls.

urlifyHashtags(_text) : String {
let hashtagRegex = /^#([a-zA-Z0-9]+)/g;
let tempText = _text.replace(hashtagRegex, " <a [routerLink]=\"['/search/hash/aaa']\" routerLinkActive=\"active-link\">#$1</a>");
var hashtagRegex2 = /([^&])#([a-zA-Z0-9]+)/g;
tempText = tempText.replace(hashtagRegex2, "<a [routerLink]=\"['/search/hash/' , 'Russ']\" routerLinkActive=\"active-link\"> #$2</a>");
return tempText;
}

And this is where it goes to:

    <p *ngIf="!editable" [innerHTML] ="item.body | bodyHashtag"></p>

Any help/advice much appreciated.

2

There are 2 answers

5
Günter Zöchbauer On

Angular doesn't process HTML added dynamically. Event though you might be able to add the HTML using the method micronyks explained, Angular won't make an router link from this HTML. Angular only processes HTML (except sanitization for security purposes) for HTML added statically to a components template.

What you can do though is to create bound values dynamically

<a [routerLink]="someStringFromComponentClass" routerLinkActive="active-link">{{boundValue}}</a>

If you actually need to build this dynamically, you can create and add a component at runtime like explained in How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

1
micronyks On

You must sanitize your HTML while injecting HTML using [innerHTML], by using DomSanitizer provider with SafeHtml.

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser'


export class myCustomPipe implements PipeTransform 
{
    constructor(private sanitized: DomSanitizer) {}

    transform(value: string): SafeHtml{
       return this.sanitized
                  .bypassSecurityTrustHtml(this.urlifyHashtags(value));
    }

    urlifyHashtags(_text) : String {
            let hashtagRegex = /^#([a-zA-Z0-9]+)/g;
            let tempText = _text.replace(hashtagRegex,"<a [routerLink]=\"['/search/hash/aaa']\" routerLinkActive=\"active-link\">#$1</a>");
            var hashtagRegex2 = /([^&])#([a-zA-Z0-9]+)/g;
            tempText = tempText.replace(hashtagRegex2, "<a [routerLink]=\"['/search/hash/' , 'Russ']\" routerLinkActive=\"active-link\"> #$2</a>");
            return tempText;
     }

}