'Angular/Typescript Text with routerLink

Updated Question for more Clarity:

Need to display some texts and links as innerHTML(data from service/DB) in the Angular HTML and when user clicks, it should go to Typescript and programmatically navigates by router.navigate

Also, How to add DomSanitizer from @ViewChild/ElementRef

Added all example in below code

Here is the updated stackblitz code

As shown in screenshot from angular.io some texts and some links

enter image description here



Solution 1:[1]

You have a css problem.

  1. <a href="something"></a> looks like a link
  2. <a [routerLink]="something"></a> looks like a link, because if you inspect the HTML it actually gets an href property added because of routerLink
  3. <a (click)="goTo()"></a> does NOT look like a link, because there is no href

Chrome and Safari default user agents css will not style <a> without an href (haven't confirmed Firefox but I'm sure its likely). Same thing for frameworks like bootstrap.

Updated stackblitz with CSS moved to global, not app.css https://stackblitz.com/edit/angular-ivy-kkgmkc?embed=1&file=src/styles.css

This will style all links as the default blue, or -webkit-link if that browser supports it. It should be in your global.css file if you want it to work through the whole app.

a {
  color: rgb(0, 0, 238);
  color: -webkit-link;
  cursor: pointer;
  text-decoration: underline;
}

Solution 2:[2]

this works perfectly for me :D

 @Directive({
  selector: "[linkify]",
})

// * Apply Angular Routing behavior, PreventDefault behavior
export class CustomLinkDirective {
  @Input()
  appStyle: boolean = true;
  constructor(
    private router: Router,
    private ref: ElementRef,
    @Inject(PLATFORM_ID) private platformId: Object
  ) {}

  @HostListener("click", ["$event"])
  onClick(e: any) {
    e.preventDefault();
    const href = e.target.getAttribute("href");
    href && this.router.navigate([href]);
  }

  ngAfterViewInit() {
    if (isPlatformBrowser(this.platformId)) {
      this.ref.nativeElement.querySelectorAll("a").forEach((a: HTMLElement) => {
        const href = a.getAttribute("href");
        href &&
          this.appStyle &&
          a.classList.add("text-indigo-600", "hover:text-indigo-500");
      });
    }
  }
}

HOW I USE IT

 <p linkify
     class="mt-3 text-lg text-gray-500 include-link"
     [innerHtml]="apiSectionText"
   ></p> 

result

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 k-coding