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>';
  }

}
7
  • You probably have to bypass angular's security mechanisms. check this Commented Apr 25, 2018 at 8:11
  • 2
    @ochs.tobi please remove your comment. That's error inducing and completely false. Commented Apr 25, 2018 at 8:14
  • Please refer https://stackoverflow.com/a/41979685/7458082 Commented Apr 25, 2018 at 8: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 Commented Apr 25, 2018 at 8:18
  • something like this npmjs.com/package/ng-dynamic-component Commented Apr 25, 2018 at 8:22

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.