How to fix angular app reloading on normal hyperlink when it is inserted via innerHtml property?

天涯浪子 提交于 2019-12-11 15:18: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


回答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.



来源:https://stackoverflow.com/questions/55941217/how-to-fix-angular-app-reloading-on-normal-hyperlink-when-it-is-inserted-via-inn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!