【问题标题】:How to dynamically create div with dynamic Id in angular 4如何在角度 4 中动态创建具有动态 ID 的 div
【发布时间】:2018-04-25 08:07:24
【问题描述】:

我正在尝试使用打字稿添加带有 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>';
  }

}

【问题讨论】:

标签: angular


【解决方案1】:

为此提供一个遮阳篷,即使它可能不是最佳解决方案。 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>

【讨论】:

    猜你喜欢
    • 2018-02-20
    • 1970-01-01
    • 2011-03-25
    • 1970-01-01
    • 1970-01-01
    • 2011-12-17
    • 2016-04-29
    • 2022-01-17
    • 2015-01-03
    相关资源
    最近更新 更多