通过类选择器呈现Angular2组件

时间:2016-04-27 11:56:17

标签: angular angular2-template

我的问题很简单,但请相信我,我一直想把它包围好几个小时。

有一个组件可以通过类选择器进行实例化。

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

有没有办法通过非元素选择器动态加载组件?

2 个答案:

答案 0 :(得分:3)

这不应该奏效。组件和指令仅适用于静态添加的标记,属性和类。

如果您想动态添加/删除组件和指令,请使用DynamicComponentLoaderViewContainerRefcreateComponent()

答案 1 :(得分:-1)

为什么它不起作用是因为当你使用[class]时,它意味着“class”是一个attr而不是将“mycomponent”类赋给div。