0

I would like to insert this kind of code:

template = '<div style="background-image: url("/assets/images/hello_message.png");">TEST</div>'

but as soon as I inject it that way:

@ViewChild('root', { static: true }) element: HTMLDivElement;


ngOnInit(): void {
  this.element.nativeElement.innerHTML = this.template;
}

it's getting parsed as

<div style="background-image: url(" assets="" images="" hello_message.png");"="">TEST</div>

I'm aware it's not safe without any kind of sanitization but I would like to do it that way. How to do it?

1 Answer 1

1

The solution that I found after a lot of work is to use Renderer2

So my code look like this

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

 templateUrl = 'url("/assets/images/hello_message.png")'
 templateDiv = '<div">TEST</div>'

    constructor(private elmRef: ElementRef, private renderer: Renderer2) {}
    
    ngOnInit(): void {
       this.element.nativeElement.innerHTML = this.templateDiv;
      this.renderer.setStyle(this.element.nativeElement, 'background-image',this.templateUrl)    
    }

The result

<div style="background-image: background-image: url("/assets/images/hello_message.png");>TEST</div>

2 option :

template = '<div style="background-image: url("/assets/images/hello_message.png");">TEST</div>'

  ngAfterViewInit() {
    this.renderer.setProperty(this.element.nativeElement, 'innerHTML', this.
template);
  }

Hope useful

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.