Home Is it possible to insert component selector tags using string interpolation or property binding?
Reply: 1

Is it possible to insert component selector tags using string interpolation or property binding?

user9356978 Published in 2018-02-13 20:45:32Z

Suppose I have 10 components having the selectors as (had to insert full stops for preventing them from being ommitted )

<. app-comp1 .> <. app-comp2 .> ... <. app-comp10 .>

In the parent component I want to insert only one of the above ten based on a property having the name of the component. Eg. this.component = 'comp7' So I should only include <. app-comp7 .>

P.s. i know it can be accomplished by ngIf. But that would mean writing 10lines. I need to use shorter code.

vincecampanale Reply to 2018-02-13 21:37:31Z

No, it is not possible to have dynamic tags in your HTML. You don't necessarily need to have 10 *ngIf's to accomplish this kind of behavior however. Using ComponentFactoryResolver and an entry component, you can dynamically insert whichever component you want into your DOM.

An example of how this might look:

  template: `<div #entry></div>`
export class MyComponent implements AfterContentInit {
  @ViewChild('entry', {read: ViewContainerRef})
  entry: ViewContainerRef;

  constructor(private resolver: ComponentFactoryResolver) {}

  ngAfterContentInit() {
    // Get your component's class here and save it in a variable
    const dynamicComponent = some condition ? ComponentOne : ComponentTwo;
    const factory = this.resolver.resolveComponentFactory(dynamicComponent);


Note that this must happen in the AfterContentInit lifecycle hook.

Edit: In response to your comment which is that the ComponentFactoryResolver is too complex, I would argue it is much simpler than using many *ngIf directives. This moves the complexity into a simple function rather than many lines of complex markup. Unfortunately, since you cannot use dynamic HTML tags, these are the two best options for what you want to do.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.426938 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO