我正在尝试向 DOM 添加动态生成的 html 标签。 对于前。动态标签就像 -
<dynamicTag></dynamicTag>
。
调试后我发现 checkmarx 扫描由于“<" and ">”字符而失败。
代码无法进行 checkmarx 扫描。
我尝试了以下方法 -
// .html 中的父元素
<div [innerHTML]="selector"></div>
//.ts 中的逻辑
let safeTag = this.domSanitizer.bypasssecuritytrusthtml(dynamicTag);
this.selector = `<${safeTag}></${safeTag}>`
// .html 中的父元素
<div #MFE></div>
//.ts 中的逻辑
let el = this.MFE.nativeElement;
this.selector = `<${safeTag}></${safeTag}>`
el.innerHTML = this.selector;
// .html 中的父元素
<div #MFE></div>
//.ts 中的逻辑
let el = this.MFE.nativeElement;
this.selector = `<${safeTag}></${safeTag}>`
el.insertAdjacentHTML("beforeend", this.selector);
// .html 中的父元素
<div #MFE></div>
//.ts 中的逻辑
let el = this.MFE.nativeElement;
this.selector = `$lt;${safeTag}$gt;$lt;/${safeTag}$gt;`
el.innerHTML = this.selector;
动态标签是动态生成的,并作为参数传递给一个方法,在该方法中我尝试了上面提到的方法。
您可以使用
Renderer2
Angular 的转到功能来插入经过清理的内容。我们使用 createElement
生成标签,然后使用 appendChild
插入,工作示例如下!
import { Component, ElementRef, Renderer2, ViewChild } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
@Component({
selector: 'app-root',
standalone: true,
template: `
<div #MFE></div>
`,
})
export class App {
@ViewChild('MFE') mfe!: ElementRef<any>;
dynamicTag = 'h1';
constructor(private renderer: Renderer2) {}
ngAfterViewInit() {
const safeTag = this.renderer.createElement(this.dynamicTag);
safeTag.textContent = 'dynamically generated!';
this.renderer.appendChild(this.mfe.nativeElement, safeTag);
}
}
bootstrapApplication(App);