How to fix angular app reloading on normal hyperli

2019-08-20 02:34发布

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

2条回答
爷的心禁止访问
2楼-- · 2019-08-20 02:58

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>

查看更多
做自己的国王
3楼-- · 2019-08-20 03:19

Try using routerLink instead of href.

查看更多
登录 后发表回答