在Angular 7中,可以使用innerHTML属性从数据库渲染HTML标签。以下是一个示例解决方法:
import { Component, OnInit } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { YourService } from 'your-service';
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
styleUrls: ['./your-component.component.css']
})
export class YourComponent implements OnInit {
renderedHtml: SafeHtml;
constructor(private sanitizer: DomSanitizer, private yourService: YourService) { }
ngOnInit() {
this.yourService.getHtmlFromDatabase().subscribe(html => {
this.renderedHtml = this.sanitizer.bypassSecurityTrustHtml(html);
});
}
}
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class YourService {
constructor(private http: HttpClient) { }
getHtmlFromDatabase() {
return this.http.get('your-api-url');
}
}
请确保将'your-api-url'替换为从数据库获取HTML标签的API端点的实际URL。
这样,当组件初始化时,它将从YourService中获取HTML标签的数据,并使用DomSanitizer服务将其安全地渲染到组件的HTML模板中的