Angular 2 Directives and DOM manipulation

Struggling to find a solution for this.

I am trying to replace the innerHtml of an element with html that was generated from another library. Seems simple enough but not with Angular 2 of course. I am basically wrapping google-prettify-code script in an Angular 2 app directive.

in the component html that contains my prettify directive I want to add something like this.

<pre dg-prettify>
    &lt;div class=&quot;foobar&quot;&gt;
     &lt;div&gt;Hello World&lt;/div&gt;
   &lt;/div&gt;
</pre>

Then inside my prettify directive I need to take the innerHtml of the pre tag and pass it to the external library to be processed. I will get back a decoded html structure that then needs to be injected into the innerHtml of the pre tag replacing it’s original content .

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

If the component HTML contents are static, something like this should work: @Directive({ selector: '[dg-prettify]' }) export class Prettify { constructor(private elRef:ElementRef) {} ngOnInit() { let innerHTML = this.elRef.nativeElement.innerHTML; console.log(innerHTML); // call 3rd-party library let newHtml = someExternalLibraryFunction(innerHtml); this.elRef.nativeElement.innerHTML = newHtml; } } @Component({ selector: 'my-app', template: `<pre dg-prettify> &lt;div class=&quot;foobar&quot;&gt; &lt;div&gt;Hello World&lt;/div&gt; &lt;/div&gt; </pre>`, directives: [Prettify] }) export class AppComponent { constructor() { console.clear(); } Plunker If the component HTML content is dynamic, then pass that content to the directive as a string input property, and implement lifecycle hook ngOnChange() to update the innerHTML whenever the content changes.