【问题标题】:Angular 7+: Inject static html file into middle of component viewAngular 7+:将静态 html 文件注入组件视图的中间
【发布时间】:2019-09-05 06:48:40
【问题描述】:

我无法找到将静态 html 从文件注入到视图中间的最佳方法。我有一个名为 eula-dialog 的组件,其中该组件尚未执行任何操作,但视图如下所示: eula-dialog.component.html

<h1 md-dialog-title>Sign EULA</h1>
<mat-dialog-content>

  <!-- HOW TO INJECT A FILE HERE -->
  <div> REPLACE ME WITH CONTENTS OF FILE</div>


</mat-dialog-content>
<mat-dialog-actions>
  <mat-checkbox [(ngModel)]="agreeCheckbox">I have read and agree to the eula</mat-checkbox>
  <button md-raised-button color="primary" mat-dialog-close [disabled]="!agreeCheckbox">
    I Agree
  </button>
</mat-dialog-actions>

我的文件夹结构如下所示:

eula-dialog
    eula-dialog.component.html
    eula-dialog.component.scss
    eula-dialog.component.spec.ts
    eula-dialog.component.ts
    very-long-readonly-eula-template.html

我无法修改eula HTML的内容,它主要有文本和一些html元素,但不是一个完整的页面,它看起来像这样:

<p>Title</p>
<div> LOTS OF TEXT </div>

最好的方法是什么? 此外,最好不要将此 eula html 文件/模板始终与应用一起加载,而仅在需要时发送给客户端。

【问题讨论】:

  • 使用httpClient 和“文本”作为内容类型来获取文件并使用[innerHTML] 进入您的页面?
  • 谢谢@Gilsdav,您对以下答案的评论效果很好

标签: html angular angular-material


【解决方案1】:

将静态文件放在 assets 文件夹中,否则告诉 angular 将其标记为 angular.json 中的资产。

然后使用

<h1 md-dialog-title>Sign EULA</h1>
<mat-dialog-content>

  <!-- HOW TO INJECT A FILE HERE -->
  <div [innerHTML]="eulaContent">...</div>


</mat-dialog-content>
<mat-dialog-actions>
  <mat-checkbox [(ngModel)]="agreeCheckbox">I have read and agree to the eula</mat-checkbox>
  <button md-raised-button color="primary" mat-dialog-close [disabled]="!agreeCheckbox">
    I Agree
  </button>
</mat-dialog-actions>
// In .ts file
import { DomSanitizer} from '@angular/platform-browser';

eulaContent = '';

constructor(private sanitizer: DomSanitizer)

ngOnInit(){
  fetch('/assets/yourlocation.html').then(res => res.text()).then(data => {
    this.eulaContent = this.sanitizer.bypassSecurityTrustHtml(data);
  })
}

【讨论】:

  • 我用了const headers = new HttpHeaders().set('Content-Type', 'text/html'); HttpClient.get(url, {headers, responseType: 'text'} 而不是fetch 但这行得通,非常感谢
猜你喜欢
  • 2019-10-30
  • 1970-01-01
  • 2020-04-02
  • 2017-12-09
  • 2018-06-08
  • 1970-01-01
  • 1970-01-01
  • 2020-04-16
  • 2011-07-29
相关资源
最近更新 更多