9

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.

3 Answers 3

24

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>
4
  • Thanks for the answer. Do you think it works to set script also? Oct 15, 2018 at 17:57
  • 1
    I haven't tried that. But I don't think it would. To avoid XSS, Angular would block/strip the content to make it safe. Not completely sure though. Please give it a try on StackBlitz
    – SiddAjmera
    Oct 15, 2018 at 17:59
  • 1
    Shouldn't you be doing your nativeElement manipulation inside ngAfterViewInit? I once read that doing this inside ngOnInit could result the element being undefined. Not sure if that's only true for components. May 4, 2020 at 18:48
  • Thanks for the comment. I've updated the answer. :)
    – SiddAjmera
    May 6, 2020 at 5:44
0

Just fixed it with the following:

el.nativeElement.innerHTML = '<p>Hello World<p>';

I realized the nativeElement should accept all the JavaScript methods as it is native HTML element.

0

Appending text can also be achieved by using createText property of renderer2 object.

    import {ElementRef, ViewChild, Renderer2} from '@angular/core';


export class AdvertisementDirective {

  @ViewChild('templateRefName') el: ElementRef;

  constructor(
    private renderer: Renderer2
  ) {
  }

  ngOnInit() {

   const text = this.renderer.createText('Hello World'); // <-- TO Be Noted
    this.renderer.appendChild(this.el.nativeElement, text);

  }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.