【发布时间】:2018-08-30 14:51:34
【问题描述】:
我有以下字符串,我已绑定到 DOM 元素的“innerHTML”。我已经对其进行了消毒,因此浏览器不会将其删除。路由器链接不工作。如果我将其更改为 href 那么它确实有效。如何让 Angular 绑定此链接?
正在绑定的 HTML 字符串
<a routerLink='/somelink'>Something</a>
【问题讨论】:
标签: html angular dom angular2-routing
我有以下字符串,我已绑定到 DOM 元素的“innerHTML”。我已经对其进行了消毒,因此浏览器不会将其删除。路由器链接不工作。如果我将其更改为 href 那么它确实有效。如何让 Angular 绑定此链接?
正在绑定的 HTML 字符串
<a routerLink='/somelink'>Something</a>
【问题讨论】:
标签: html angular dom angular2-routing
routerLink='/somelink' 是一种告诉 Angular 在您单击链接时如何行为的方式。
这不是原生的 Javascript 行为。
如果您使用 innerHTML 将其添加到您的组件中,这将永远不会起作用。使用routerLink='/somelink' 仅在您的代码未编译时有效。
为了形象化这一点,让我们以(click) 为例,因为它是相同的情况。看下面的sn-p:
<button (click)="alert('working')">(click)</button>
<button onclick="alert('working')">onclick</button>
点击两个按钮,看看哪个有效。这是因为 Angular 会根据其语法编译您的代码。 routerLink 是其语法的一部分,而不是原生 Javascript 的一部分。
【讨论】:
routerLink 在编译后的代码中与(click) 一样有效。 (click) 是处理点击元素的原生方式吗?你认为你可以在 javascript 文件中的属性上写这个吗?
我发现这段代码可以在运行时动态编译 routerLink。我试过了,效果很好。
function createComponentFactory(compiler: Compiler, metadata: Component): Promise<ComponentFactory<any>> {
const cmpClass = class DynamicComponent {};
const decoratedCmp = Component(metadata)(cmpClass);
@NgModule({ imports: [CommonModule, RouterModule], declarations: [decoratedCmp] })
class DynamicHtmlModule { }
return compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule)
.then((moduleWithComponentFactory: ModuleWithComponentFactories<any>) => {
return moduleWithComponentFactory.componentFactories.find(x => x.componentType === decoratedCmp);
});
}
【讨论】:
这里是Angular documentation的链接,以及一个例子:
<a [routerLink]="['/yourpath']">Your Route</a>
【讨论】: