通过 class 选择器渲染 Angular2 组件

Rendering Angular2 components by class selector

我的问题很简单,但请相信我,几个小时以来我一直在努力思考这个问题。

有一个组件要通过 class 选择器实例化。

@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。我希望我可以使用它。

有什么方法可以通过非元素选择器动态加载组件吗?

那是行不通的。组件和指令仅适用于静态添加的标签、属性和 类.

如果你想动态地 add/remove 组件和指令使用 DynamicComponentLoader or createComponent() of ViewContainerRef

为什么它不起作用是因为当你使用 [class] 时,这意味着 "class" 是一个属性,没有将 "mycomponent" class 分配给 div.