我正在尝试使用typescript添加带有id的div,但它没有分配它。我只得到div
app.component.html
<div class="one" [innerHtml]="htmlToAdd">
</div>
app.component.ts
import { Component } from '@angular/core';
import { Http } from '@angular/http';
import * as shape from 'd3-shape';
import { ElementRef } from '@angular/core';
declare var $: any;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
ngOnInit() {
this.addDiv()
}
addDiv(){
this.htmlToAdd = '<div class="two" id="myId">my div</div>';
}
}
答案 0 :(得分:0)
要给它一个灵感,即使它可能不是一个最佳的解决方案。 Here is a Stackblitz
在您的组件中
trustedHtml: SafeHtml;
constructor(public s: DomSanitizer) {}
ngOnInit() {
this.addDiv();
}
public addDiv() {
this.trustedHtml = this.s.bypassSecurityTrustHtml("<div class='two' id='myId'>my div</div>")
}
和你的Html
<div [innerHTML]="trustedHtml"></div>