3

My question is simple, but believe me, I've been trying to wrap my head around it for hours now.

There's a component that's to be instantiated via a class selector.

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

Let's say the parent Component looks like this:

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

Why is it that the second version is never rendered? How would I make it render? Is this a change detection issue or is it just not supposed to work this way? I've played around with the change detection strategy, which didn't have any effect. Also I've come across DynamicComponentLoader. My hopes are that I can get around using it.

Is there any way to load components dynamically via non-element selectors?

j2L4e
  • 6,914
  • 34
  • 40

2 Answers2

3

That is not supposed to work. Components and directives are only applied to statically added tags, attributes and classes.

If you want to dynamically add/remove components and directives use DynamicComponentLoader or createComponent() of ViewContainerRef

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Is this the same for something like: `
    – Zze Jan 19 '17 at 00:57
  • Yes exactly, because dynamic HTML like your example doesn't work for selectors. See also http://stackoverflow.com/questions/36325212/angular-2-dynamic-tabs-with-user-click-chosen-components/36325468#36325468 – Günter Zöchbauer Jan 19 '17 at 04:08
-1

Why it's not work is because when you use [class],it's meaning that "class" is an attr not assigning "mycomponent" class to div.