本文介绍了Angular 5将动态HTML文件添加到DIV中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Angular非常陌生,我试图将html文件作为字符串插入到DIV元素中

I am very new to Angular, I am trying to insert the html file as my string and insert into DIV element

我的 search.component.html 被称为

<div #ID></div>

components.ts

components.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中并显示内容,标记也可以具有内联样式.

I am getting the response from server as complete html markup, Just I need to append into my DOM and display the content, the markup can have inline styles also.

我尝试了< div [innerHTML] ="ServerResponseHtml"></div>和< div innerHTML ="{{ServerResponseHtml}}"></div> ,但这未显示为html,而是显示为文本.

I tried for <div [innerHTML]="ServerResponseHtml"></div> and <div innerHTML="{{ServerResponseHtml}}"></div> but this is not displaying as html it is displayed as text.

推荐答案

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

We need to use the safehtml for displaying the html.

  1. 我们需要为此创建Pipe. 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 我们需要导入管道
  1. component.tsWe need to import the pipe

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

import {Component, NgModule, Pipe, PipeTransform} from '@angular/core'

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>';
  }
}

希望这会有所帮助:).

Hope this helps :).

这篇关于Angular 5将动态HTML文件添加到DIV中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 14:01