问题描述
我有一个具有message
属性的警报组件.该消息可能是带有超链接的某些文本:
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</>
通过innerHtml
插入message
:
<div class="alert-text" [innerHtml]="alert.message"></div>
当我单击链接时,它将重新加载应用程序.我该怎么做才能解决此问题?
When I click the link, it reloads the app. What can I do to fix this?
角度: 7.1.0
推荐答案
innerHTML不绑定任何角度事件,这就是为什么它不起作用的原因要使其正常工作,您需要创建负责路线导航的自定义指令.
innerHTML does not bind any angular event that's why it's not workingto make it work you need to create custom directive which is responsible for route navigation.
检查工作示例- https://stackblitz.com /edit/skdroid-innerhtml-routing
自定义指令-CustomRouteDirective
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代码-<div appCustomRoute [innerHTML]="sampleHTML"></div>
这篇关于通过innerHtml属性插入普通超链接时,如何解决角度应用重新加载的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!