How to dynamically add innerHTML using angular 2 components

I am creating documents for a component library. I want 1 html line that generates both the component on the page and the documents for it.

What I want:

enter image description here

What I have:

enter image description here

When I check the HTML, there are no button tags. They are deleted when I use innerHTML.

My component code:

private flatButtons = `<div class="button-wrapper"> <my-button [type]="'default'" [raised]="false">Default</my-button> </div> <div class="button-wrapper"> <my-button [type]="'primary'" [raised]="false">Primary</my-button> </div> <div class="button-wrapper"> <my-button [type]="'success'" [raised]="false">Success</my-button> </div> <div class="button-wrapper"> <my-button [type]="'info'" [raised]="false">Info</my-button> </div> <div class="button-wrapper"> <my-button [type]="'warning'" [raised]="false">Warning</my-button> </div> <div class="button-wrapper"> <my-button [type]="'danger'" [raised]="false">Danger</my-button> </div>` constructor() {} getCode() { return html_beautify(this.flatButtons, this.options) } 

My HTML template:

 <div class="row"> <div class="col-sm-6 col-xs-12"> <mi-card title="Flat Buttons" baCardClass="with-scroll button-panel"> <div id="flatButtons" [innerHTML]="getCode()"> </div> </mi-card> </div> <div class="col-sm-6 col-xs-12"> <pre>{{getCode()}}</pre> </div> 

+5
source share
2 answers

Angular does not process the dynamically added HTML file, it simply adds it verbatim, except for some sanitation, to prevent security problems. See In RC.1, some styles cannot be added using binding syntax to prevent the sanitizer from removing HTML.

You can use ViewContainerRef.createComponent() , as shown in Angular 2 dynamic tabs, using the components you select to dynamically add components.

There are also solutions for creating components dynamically, as shown in the $ Compilation Equivalent in Angular 2

+4
source

I agree with Gunther's answer as he answers my question.

For those who are interested in how I solved my problem, this is to create a component and require it.

I created a dumb component:

 import {Component} from '@angular/core'; @Component({ selector: 'flat-buttons', template: require('./flatButtons.html'), }) export class FlatButtons { constructor() { } } 

And then my modified html template:

 <div class="col-sm-6 col-xs-12"> <mi-card title="Flat Buttons" baCardClass="with-scroll button-panel"> <flat-buttons></flat-buttons> </mi-card> </div> <div class="col-sm-6 col-xs-12"> <h3>Code Snippet</h3> <div class="well"> <pre>{{getFlatButtons()}}</pre> </div> </div> 

And my modified component code:

 private flatButtons = require('./components/flatButtons/flatButtons.html') constructor() {} getFlatButtons() { return html_beautify(this.flatButtons, this.options) } 
0
source

Source: https://habr.com/ru/post/1259421/


All Articles