How to dynamically add innerHTML with angular 2 components

前端 未结 2 2143
鱼传尺愫
鱼传尺愫 2020-11-27 23:06

I\'m creating docs for a component library. I want 1 string of html that generates both the component on the page and the docs for it.

What I want:

相关标签:
2条回答
  • 2020-11-27 23:30

    Angular doesn't process HTML added dynamically, it just adds it verbatim except some sanitization to prevent security issues. See In RC.1 some styles can't be added using binding syntax for how to prevent the sanitizer of stripping the HTML.

    You can use ViewContainerRef.createComponent() like shown in Angular 2 dynamic tabs with user-click chosen components to add components dynamically.

    There are also solutions available how to create components dynamically like shown in Equivalent of $compile in Angular 2

    0 讨论(0)
  • 2020-11-27 23:32

    I'll accept Gunter's answer since it answers my question.

    For those who are interested, the way I solved my problem was by creating a component and requiring 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 讨论(0)
提交回复
热议问题