我需要访问通过Angular中的innerHTML指令动态创建的组件的DOM元素。 这是我的主要组成部分:
import {Component} from '@angular/core';
@Component({
selector: 'app-root',
template: `
<app-block [template]="template"></app-block>
`
})
export class AppComponent {
protected template = `
<main role="main" class="inner cover">
<h1 class="cover-heading text-center">Cover your page.</h1>
<p #paragraph class="lead">Cover is a one-page template for building simple and beautiful home pages.
Download, edit the text, and add your own fullscreen background photo to make it your own.</p>
<p #paragraph class="lead">
<a href="#" class="btn btn-lg btn-secondary">Learn more</a>
</p>
</main>
`;
}
这是我动态创建的组件:
import {
AfterViewInit,
Component,
Input,
ViewChildren,
} from '@angular/core';
@Component({
selector: 'app-block',
template: `
<div [innerHTML]="template"></div>
`
})
export class BlockComponent implements AfterViewInit {
@Input() template: String;
@ViewChildren('paragraph') ps;
public ngAfterViewInit(): void {
console.log(this.ps.length);
}
}
我只是尝试获取对象的长度,但是它似乎是空的。好像看不到自动生成的模板。
答案 0 :(得分:0)
默认情况下,Angular不允许您将动态HTML注入模板中,这是出于安全考虑(跨站点脚本,请阅读here)。
但是,您可以绕过上面链接的文档中提到的消毒,使用管道将是最直接的解决方案:
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Pipe({name: 'safeHTML'})
export class SanitizeHtml implements PipeTransform {
constructor(private sanitizer: DomSanitizer) {}
transform(html): SafeHtml {
return this.sanitizer.bypassSecurityTrustHtml(html);
}
}
您将编辑模板以使用该管道: