html - Angular 5 将动态 html 文件添加到 DIV 中

标签 html angular

我是 Angular 的新手,我正在尝试将 html 文件作为我的字符串插入到 DIV 元素中

我有我的 search.component.html

<div #ID></div>

组件.ts

import { Component} from '@angular/core';

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.scss']
})
export class SearchComponent {
  constructor() {}

  let ServerResponseHtml = '<div><input type="text"/><input type="text"/><span class="btn btn-outline-primary btn-sm" (click)="open(content)">View Document</span></div>';

  document.getElementById("DIV").innerHTML = ServerResponseHtml;
}

我从服务器得到的响应是完整的 html 标记,我只需要附加到我的 DOM 中并显示内容,标记也可以有内联样式。

我试过 <div [innerHTML]="ServerResponseHtml"></div> and <div innerHTML="{{ServerResponseHtml}}"></div>但这不是显示为 html,而是显示为文本。

最佳答案

我们需要使用 safehtml 来显示 html。

  1. 我们需要为此创建管道。 safe-html-pipe.ts
    import {DomSanitizer, SafeHtml} from '@angular/platform-browser';
    import {Pipe, PipeTransform} from '@angular/core';
    
    @Pipe({name: 'safehtml'})
    
    export class SafeHtmlPipe implements PipeTransform {
      constructor(private sanitized: DomSanitizer) {
      }
    
      transform(value): SafeHtml {
        return this.sanitized.bypassSecurityTrustHtml(value);
      }
    }
  1. component.ts 我们需要导入管道

从'@angular/core'导入{Component, NgModule, Pipe, PipeTransform}

import {BrowserModule} from '@angular/platform-browser'
import { FormsModule } from '@angular/forms';
import { DomSanitizer } from '@angular/platform-browser'
import { SafeHtmlPipe } from './safe-html-pipe';
@Component({
selector: 'app-root',
template: 
    `<div [innerHtml]="safeHtmlContent | safehtml">
 </div>"})`
 
export class AppComponent {
 name:string;
  safeHtmlContent : string;
  constructor() {
    this.name = 'Angular2'
    this.safeHtmlContent  = '<html><head><title>Hello safe</title></head><body><h1>hello world Hello Umesh</h1></body></html>';
  }
}

希望这有帮助:)。

关于html - Angular 5 将动态 html 文件添加到 DIV 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48339039/

相关文章:

javascript - 将颜色放在 div 背景之上? (又名更改 div 的颜色而不更改 'background-color' 值)

angular - 另一个 View angular2 的隐藏按钮

angular - Facebook 分享按钮问题 : "Attachment not found: The attachment could not be found."

angular - app.shared.module.ts 和 app.server.module.ts 之间的差异

php - 仅从主页删除 div 类

javascript - jQuery 或 Javascript 如何查找 Rails 表单中的复选框是否已选中并删除表单 div

javascript - 将 SVG 下载为 PNG 图像

javascript - 在 Jupyter 笔记本上 Html 访问 JS 文件

angular - 如何在 Angular 5 中将 FormControl 动态添加到 FormGroup?

滚动页面时,Angular 9+ 和 ng-bootstrap 工具提示在固定元素上失败,是否有比我更好的修复方法?