How to fix angular app reloading on normal hyperli

2019-08-20 02:21发布

问题:

I've got an alert component which has a message property. The message may be some text with a hyperlink in it:

An error occured. <a href="/learn-more">Learn more</>

The message is inserted via innerHtml:

<div class="alert-text" [innerHtml]="alert.message"></div>

When I click the link, it reloads the app. What can I do to fix this?

Angular: 7.1.0

回答1:

innerHTML does not bind any angular event that's why it's not working to make it work you need to create custom directive which is responsible for route navigation.

check the working sample - https://stackblitz.com/edit/skdroid-innerhtml-routing

custom directive - CustomRouteDirective

import { Directive, ElementRef, HostListener } from '@angular/core';
import { Router } from '@angular/router';

@Directive({
  selector: '[appCustomRoute]'
})
export class CustomRouteDirective {
  constructor(private el: ElementRef, private router: Router) { }

  @HostListener('click', ['$event'])
  public onClick(event) {
    if (event.target.tagName === 'A') {
      this.router.navigate([event.target.getAttribute('href')]);
      event.preventDefault();
    } else {
      return;
    }
  }

html code - <div appCustomRoute [innerHTML]="sampleHTML"></div>



回答2:

Try using routerLink instead of href.