我对 Angular 很陌生,我正在尝试将 html 文件作为我的字符串插入并插入到 DIV 元素中
我有我的search.component.html
called
<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。
- 我们需要为此创建管道。
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);
}
}
-
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>';
}
}
希望这可以帮助 :)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)