具有功能 RouterLink 的 Angular2 Dynamic HTML

Angular2 Dynamic HTML with functional RouterLink

老用户,第一次提问!在两天的大部分时间里,我一直在努力解决这个问题,但无济于事,所以我们开始吧。

Angular2 中来自外部源的动态编译模板?

我正在使用 http 从 WordPress API 以 HTML 的形式获取页面内容。所以我有一个这样的模板:


    <div [innerHTML]="contentHTML"> </div>

和 "contentHTML" 是组件中的字符串变量,并通过 API 调用异步赋值,如下所示:


    <a routerLink="/help/faq.html"> </a>

我希望 routerLink 正常工作。当然,routerLink 可以是模板中有效的任何内容。

如果以上都不行

如果上述方法不起作用,有什么方法可以解释传入的 HTML 并动态添加 routerLinks 以替换标准 href?

经过大量挖掘,我发现 的答案对于让事情顺利进行非常有用!

秘制酱料!!!

签出 完整的 Plunker 示例 通过 yurzui 获取详细信息,但简而言之,确保创建运行时编译组件 DynamicHtmlModule class 具有对RouterModule 模块。否则动态模板中使用的 routerLink 指令将不起作用。我将下面的关键代码加粗了。

@NgModule({
  imports: [CommonModule, <strong>RouterModule</strong>],
  declarations: [decoratedCmp]}) class DynamicHtmlModule { }

  return compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule)
   .then((moduleWithComponentFactory: ModuleWithComponentFactories<any>) => {
     return moduleWithComponentFactory.componentFactories
      .find(x => x.componentType === decoratedCmp);
  });
}

对于您的模板可能使用的任何其他指令或组件也是如此。您必须确保 DynamicHtmlModule 正确引用它们才能使它们正常工作。

我遇到了同样的问题,我遵循了 this answer,但在导入 DynamicComponentModule 的代码中添加了一个简单的修改,但添加了 导入:[RouterModule]

所以步骤如下安装ng-dynamic:

npm install --save ng-dynamic

然后使用以下导入和代码:

import { DynamicComponentModule } from 'ng-dynamic';

@NgModule({
   imports: [
       ...
       DynamicComponentModule.forRoot({imports: [RouterModule]}),
       ...
   ],
   ...
})
export class AppModule {} 

然后代替:

<div [innerHTML]="contentHTML"> </div>

使用:

<div *dynamicComponent="contentHTML"></div>

希望对您有所帮助!

在使用散列位置策略时,不使用动态运行时编译的一种可能解决方案是使用以下HTML

<a onclick="window.location.reload()" href="#/pages/Home">Click</a>

其中 /pages/Home 是一条 angular 路线。这样就会设置成一个div如下

<ng-container *ngIf='content'>
  <div [innerHTML]="content.text"></div>
</ng-container>

这将触发目的地的重新加载,因此将内容移交给 angular 路由器。

更新 1

我使用自定义事件对此使用了更简洁的解决方法。我添加了一个自定义js如下

function navigate_in_primary(url) {
    var evt = new CustomEvent('content_navigate', { detail: { url: url, primary: true } });
    window.dispatchEvent(evt);
}

我在注入 app.module

的自定义服务的构造函数中使用 RxJs 监听此事件
Observable.fromEvent<Event>(window, 'content_navigate')
.subscribe((event)=>{
    this.router.navigateByUrl(event.detail.url);
})

最后,我的HTML

<a onclick="navigate_in_primary('/pages/home.aspx')" class="grey-button">SIGN IN</a>