-1

suppose i want to insert some HTML element from the server side to the component, how can i do it

import { Component, ElementRef, ViewChild, AfterViewChecked, TemplateRef, ViewContainerRef } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
<div>
<h3>this is the container</h3>
  <div #holder></div>
</div>
  `
})
export class AppComponent implements AfterViewChecked {
  @ViewChild('holder', { read: TemplateRef }) _template: TemplateRef<any>; 
  constructor() { }
  ngAfterViewChecked() {
    debugger;
    this._template.createEmbeddedView('<div>this is a new "div" element</div>');       
  }
}

in this code i am trying to insert a div to another div with the id='holder' but i am not able to achieve it.

Lijin Durairaj
  • 4,910
  • 15
  • 52
  • 85

1 Answers1

1

I got the simple way to achieve.

html

<div [innerHTML]="yourHtml"></div>

ts

public yourHtml = '<div>this is a new "div" element</div>';
Rach Chen
  • 1,322
  • 2
  • 10
  • 26
  • Was about to write this :P – Swoox Dec 22 '17 at 10:32
  • 1
    But it's not the good way to deal lool it would break pure element structure. Recommend way is use `cdk` and insert(but it only support component so it's more difficult). – Rach Chen Dec 22 '17 at 10:34
  • i think this would not work, if my dynamically attached element has some events like click attached to it – Lijin Durairaj Dec 22 '17 at 10:36
  • I'm using the `safeHtml` which check if it's not hacked html. https://stackoverflow.com/questions/39628007/angular2-innerhtml-binding-remove-style-attribute – Swoox Dec 22 '17 at 10:37
  • Why don’t you add iframe?Is your html form web service or another component supported? – Rach Chen Dec 22 '17 at 10:37
  • I suggest you to use Renderer2 class: https://angular.io/api/core/Renderer2 and change server response to model which describe html elements – pioro90 Dec 22 '17 at 10:38
  • Check out this plnkr: https://plnkr.co/edit/xducufDwLTejKGI4RT12?p=preview – Swoox Dec 22 '17 at 10:46
  • i was thinking something like this - $( ".inner" ).append( "

    Test

    " ); which we do in jQuery, is it not possible with angular4?
    – Lijin Durairaj Dec 22 '17 at 11:00
  • You can you hostlistener to handle you click or any single event what you want and your target element you append. – Rach Chen Dec 22 '17 at 11:32
  • This solution would solve your problem when you use [innerHTML]. – Rach Chen Dec 22 '17 at 11:33
  • when i use this
    and use this export class AppComponent implements AfterViewInit { yourHtml = '
    this is a new "div" element
    '; i am not able to get the click event
    – Lijin Durairaj Dec 22 '17 at 14:39
  • My meaning is observer your external component click event , I would provide code later – Rach Chen Dec 22 '17 at 15:50