2

I'm currently trying to see if in Angular 2 we can create dynamic selectors/html tags. For example, I want to do something like this:

@Component({
    selector: 'my-app' + 'variableName',
    template: `
    <container> </container>
    `,
    directives: [ContainerComponet]
})

So that I could do something like:

<my-app + {{variableName}}> <!-- the variable name would be coming from a public variable inside my component-->

In a way, the implementation of my component needs to happen several times, I know I can copy/paste what I have and have multiple components however I feel there has to be a smarter way to go.

joeCarpenter
  • 1,495
  • 4
  • 19
  • 32
  • There are some tricks to achieve something like hat by creating components dynamically at runtime. Another approach that might work for you is http://stackoverflow.com/questions/36325212/angular-2-dynamic-tabs-with-user-click-chosen-components/36325468#36325468 – Günter Zöchbauer Oct 16 '16 at 15:22
  • 1
    Something like `` is not supported at all. Angular never matches selectors of dynamically created content. There were discussions recently to support directives for selectors like `[someSelector]="boolValue ? true : null"`. – Günter Zöchbauer Oct 16 '16 at 15:52
  • Thanks Gunter! I'll look into that link – joeCarpenter Oct 16 '16 at 18:37
  • Did you ever solve this? Trying to do exactly the same as you :) – Hese Apr 07 '17 at 20:56
  • @Hese, I added an input in my component (@Input), and everytime I referenced the template I set my input. In my case it defined a property within my template, makes sense? – joeCarpenter Apr 09 '17 at 01:48
  • @eagleEye Any chance you would share some code? :) – Hese Apr 09 '17 at 12:47
  • Hi Hese, please see the sample below. Hope it helps! :) – joeCarpenter Apr 09 '17 at 21:01

1 Answers1

0

This worked for me, in my case the template was identical but it needed to changed(coloring changes) based on certain values. So in the parent component these values were set and based on that my component behaved differently

Componenet code:

sample.ts

@Component({
    selector: 'my-app-sample' 
    templateUrl: 'sample.html'
})

 @Input() myInput: MyInput;

This component and template (sample.ts), is a child of another component. In the parent template we "drop" teh sample selector: my-app-sample

Template where I drop my selector (parent):

<div>
<my-app-sample [myInput] = "anotherVariable"</my-app-sample>
</div>

Note: the anotherVariable value is set in the Component parent.

joeCarpenter
  • 1,495
  • 4
  • 19
  • 32