【问题标题】:Angular: How to implement ng-include like functionality in Angular 5?Angular:如何在 Angular 5 中实现类似 ng-include 的功能?
【发布时间】:2018-05-26 01:06:59
【问题描述】:

是否有任何功能可以根据路径在组件模板内动态呈现 html 文件?我有本地 html 文件的路径,现在我需要在组件模板中显示它的内容。在 Anular 1.x 中,我们有 ng-include,Angular5 中是否有类似的功能?

<div class="row blogdetail-container">
        {{blogSelected.description}} // currently interpolates the path
</div>

变量blogSelected.description包含html文件的路径,我想在这里替换它的内容。

【问题讨论】:

标签: javascript html angular angularjs-ng-include angular5


【解决方案1】:

好的,所以我能想到的唯一合理直接的方法是使用 http 请求来获取 html 文件的内容,然后在 [innerHtml] 属性中使用它。

private dynamicTemplate: any = ""; http.get(blogSelected.description).map((html:any) => this.dynamicTemplate = sanitizer.sanitize(html));

然后使用

<div class="row blogdetail-container" [innerHtml]="dynamicTemplate"></div>

注意 1:记得将 http 作为该组件的依赖项。

注意 2: 请记住将 sanitizer 作为此组件的依赖项

注意 3:记得在调用 http 请求之前验证 blogSelected.description 以检查它实际上是一个有效的 URL。

【讨论】:

  • blogSelected.description 是组件级别的属性,不能在导入中访问。
  • 如果这是 Angular,您可能还想在将 html 传递给 DOM 之前对其进行清理。 sanitizer.sanitize(SecurityContext.html, dynamicTemplate)
  • @vincecampanale我会更新答案:)
  • @VishalGulati 你有机会尝试一下吗?
  • @VishalGulati 不幸的是,Angular 5 中没有同类功能。有相当长的讨论here。 TLDR:它会阻止离线编译并且存在安全风险
猜你喜欢
  • 2016-11-20
  • 2018-10-08
  • 2018-10-21
  • 2019-01-02
  • 2017-08-25
  • 2014-06-29
  • 1970-01-01
  • 1970-01-01
  • 2016-08-28
相关资源
最近更新 更多