要从通过Ajax调用的HTML中去除内联CSS,您可以使用Angular的内置DOM操作功能来实现。以下是一个示例解决方法:
ElementRef
和Renderer2
类。import { Injectable, ElementRef, Renderer2 } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class AjaxService {
constructor(private http: HttpClient, private renderer: Renderer2) { }
getHtml(url: string, container: ElementRef) {
return this.http.get(url, { responseType: 'text' }).subscribe(html => {
const tempDiv = this.renderer.createElement('div');
tempDiv.innerHTML = html;
// 移除内联CSS
const elementsWithStyle = tempDiv.querySelectorAll('[style]');
elementsWithStyle.forEach(element => {
element.removeAttribute('style');
});
// 将处理后的HTML插入到容器中
this.renderer.appendChild(container.nativeElement, tempDiv);
});
}
}
import { Component, ElementRef, ViewChild } from '@angular/core';
import { AjaxService } from './ajax.service';
@Component({
selector: 'app-root',
template: `
`,
providers: [AjaxService]
})
export class AppComponent {
@ViewChild('container', { static: true }) container: ElementRef;
constructor(private ajaxService: AjaxService) { }
ngOnInit() {
const url = 'your_ajax_url';
this.ajaxService.getHtml(url, this.container);
}
}
这样,通过Ajax调用的HTML将会被获取并加载到容器元素中,同时内联CSS将会被移除。