2016-11-07 82 views
5

我正在爲組件庫創建文檔。我需要1個html字符串,它可以生成頁面上的組件和文檔。如何使用角度2組件動態添加innerHTML

我想要什麼:

enter image description here

我有什麼:

enter image description here

當我檢查HTML,我的按鈕標籤不存在。當我使用innerHTML時,它們被剝離出來。

我的組件代碼:

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) 
} 

我的HTML模板:

<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> 

+0

你期望發生的? –

+0

我期待「我想要的東西:」 – collinglass

+0

之後的圖片好吧,所以您希望添加的HTML成爲實際的Angular組件。這種方式不行。看到我的答案。 –

回答

0

我會接受岡特的答案,因爲它回答我的問題的解決方案。

對於那些有興趣的人,我解決我的問題的方式是創建一個組件並要求它。

我創建了一個愚蠢的組件:

import {Component} from '@angular/core'; 


@Component({ 
    selector: 'flat-buttons', 
    template: require('./flatButtons.html'), 
}) 
export class FlatButtons { 

    constructor() { 
    } 
} 

然後我修改HTML模板:

<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> 

而且我修改組件代碼:

private flatButtons = require('./components/flatButtons/flatButtons.html') 

constructor() {} 

getFlatButtons() { 
    return html_beautify(this.flatButtons, this.options) 
} 
+0

collinglass,你是如何flatButtons.html看起來像?你可以分享嗎? – user1892775