gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:19:13 24 4
gpt4 key购买 nike

我是 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com