2016-04-27 77 views
3

我的問題很簡單,但請相信我,我一直試圖將我的頭圍繞它幾個小時。按類選擇器渲染Angular2組件

有一個組件需要通過類選擇器實例化。

@Component({ 
    selector: '.mycomponent', 
    template: '<h1>hello!</h1>' 
}) 
export class MyComponent{} 

假設父組件是這樣的:

@Component({ 
    ... 
    template: 
     ` 
     <div class="mycomponent"></div> <!-- rendered --> 
     <div [class]="'mycomponent'"></div> <!-- not rendered --> 
     ` 
}) 
export class ParentComponent{} 

爲什麼第二個版本是從來沒有顯示?我將如何渲染它?這是一個變化檢測問題還是它不應該這樣工作? 我玩過變化檢測策略,但沒有任何效果。我也碰到過DynamicComponentLoader。我的希望是,我可以避開它。

有什麼辦法通過非元素選擇器動態加載組件?

回答

3

這不應該工作。組件和指令僅適用於靜態添加的標籤,屬性和類。

如果要動態地添加/刪除組件和指令的使用DynamicComponentLoaderViewContainerRef

+0

對於像'

Zze

+0

是的,因爲動態HTML與您的示例一樣不適用於選擇器。 http://stackoverflow.com/questions/36325212/angular-2-dynamic-tabs-with-user-click-chosen-components/36325468#36325468 –

-1

createComponent()爲什麼它不工作,因爲當你使用[類],它的意思是「一流」是一個屬性未分配「 mycomponent「類到div。