Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set HTML content in the ElementRef (nativeEelement)?

I want to set the content of HTML element with directive.

export class AdvertisementDirective {

  constructor(el: ElementRef) {
    el.nativeElement.style.background = 'yellow';
    el.nativeElement.content = '<p>Hello World<p>';
  }

}

But it does not work and doesn't give any error.

The idea behind doing this is to have Ad code in the directive and set it wherever I used directive attribute. The code for advertisement contains JavaScript and HTML code.

like image 941
Maihan Nijat Avatar asked Oct 15 '18 16:10

Maihan Nijat


Video Answer


1 Answers

DOM Manipulations via directly changing properties on the nativeElement is not considered as a good practice. It's also not going to work in some cases like Web Workers and Server Side Rendering using Angular Universal.

A safer way of doing this is using Renderer2.

import { ..., AfterViewInit, ElementRef, ViewChild, Renderer2, ... } from '@angular/core';
...
export class AdvertisementDirective implements AfterViewInit {

  @ViewChild('templateRefName') el: ElementRef;

  constructor(
    private renderer: Renderer2
  ) {
  }

  ngAfterViewInit() {
    this.renderer.setStyle(this.el.nativeElement, 'background', 'yellow');
    this.renderer.setProperty(this.el.nativeElement, 'innerHTML', '<p>Hello World<p>');
  }

}

And in template:

<div #templateRefName></div>
like image 200
SiddAjmera Avatar answered Nov 08 '22 01:11

SiddAjmera