R
R
Roman Khegay2020-07-10 13:45:40
Angular
Roman Khegay, 2020-07-10 13:45:40

Correct way to render HTML/CSS inside a component received from the server?

When developing an application on Angular 9, I ran into a problem with displaying HTML and CSS received from a third-party server.

To the point:

Inside the application there is a component with ad units.
Each ad unit consists of several parts that can change dynamically:

Ad unit properties
selectedTemplate: AdvertTemplate = null
selectedCharacter: AdvertCharacter = null
headline: string = ''
description: string = ''


  • selectedTemplate - объект, внутри которого html и css
  • selectedCharacter - объект, внутри которого путь к изображению
  • headline - строка с заголовком
  • description - строка с описанием




With the API, the application receives an array with AdvertTemplate objects and a separate array with AdvertCharacter

AdvertTemplate, something like this (but may be different):
Object received from the server
html:
<div class="tpl">
   <h1 class="tpl__head">{{ title }}</h1>
   <img class="tpl__img" src="{{ img }}">
</div>

css:
.tpl {
    display: flex;
}

.tpl__head {
    font-size: 2rem;
}

.tpl__img {
    display: block;
    width: 10rem;
    height: auto;

    border-radius: 50rem;
}


The user selects the desired template from the pictures saved in advance, enters text and selects AdvertCharacter. The application should show in real time the changing of the template, character and titles.

The first path I took:


I got all the templates, and when the user selected the desired template, using DomSanitizer, I inserted the HTML into the block I needed using [innerHTML] .

Issue: All variables inside {{ }} were displayed as text and the application could not interact with them. Didn't even get to CSS.


The second way I searched on SO:

I tried to use Dynamic component loader
, but I couldn't figure out how rendering works. From different angles, various types of errors fell out into the console.


---
Question: is it possible to somehow collect a template, change data in it without dancing with a tambourine?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Murashkin, 2020-07-11
@alex_romanov116

You need to use Jit Compiler, at runtime, (significantly increase the size of the bundle, it is desirable to take it to lazy)
Stackblitz example: https://stackblitz.com/github/lyczos/angular-dynam...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question