0

I am trying to add div with id using typescript but it is not assigning it. I am only getting 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>';
  }

}
  • You probably have to bypass angular's security mechanisms. [check this](https://angular.io/guide/security) – Fussel Apr 25 '18 at 08:11
  • 2
    @ochs.tobi please remove your comment. That's error inducing and completely false. –  Apr 25 '18 at 08:14
  • Please refer [https://stackoverflow.com/a/41979685/7458082](https://stackoverflow.com/a/41979685/7458082) – Basavaraj Bhusani Apr 25 '18 at 08:16
  • you cannot add dynamic HTML via innerHTML in angular even with domsanitizer . it just renders the HTML as markup. You need something like dynamic component loading – Niladri Apr 25 '18 at 08:18
  • something like this https://www.npmjs.com/package/ng-dynamic-component – Niladri Apr 25 '18 at 08:22
  • @Niladri yes you can, but that's not recommended. Instead of advising a library, you should start by looking at the **[renderer](https://angular.io/api/core/Renderer2)**, which can do that for you. –  Apr 25 '18 at 08:32
  • @trichetriche there is also `ngComponentOutlet` in angular 4 – Niladri Apr 25 '18 at 08:33

1 Answers1

0

To give this an awnser, even tho it might not be an optimal solution. Here is a Stackblitz

In your component

trustedHtml: SafeHtml;

constructor(public s: DomSanitizer) {}

ngOnInit() {
    this.addDiv();
}

public addDiv() {
    this.trustedHtml = this.s.bypassSecurityTrustHtml("<div class='two' id='myId'>my div</div>")
}

and your Html

<div [innerHTML]="trustedHtml"></div>
Fussel
  • 1,740
  • 1
  • 8
  • 27