Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 component dynamic name

How i can set dynamic name to angular 2 component?

I have next code in my template:

<{{component} [data]="data" [anotherData]="anotherData"></{{component}}>

And I want do define componentName in my class

component: string = 'component';

Because now i have next error:

Uncaught (in promise): Template parse errors:
Unexpected closing tag "{{component}" ("
like image 420
Max K Avatar asked Jul 16 '16 13:07

Max K


3 Answers

<div  [ngSwitch]="contactService.contact.cat">
        <div *ngSwitchWhen="'person'">
            <persons-edit [primary]="true"></persons-edit>
        </div>
        <div *ngSwitchWhen="'business'">
            <businesses-edit [primary]="true"></businesses-edit>
        </div>
        <div *ngSwitchWhen="'place'">
            <places-edit [primary]="true"></places-edit>
        </div>
    </div>

This is what I use in my app. I have the three components defined, and use a switch to show the one I want. I get the selection here from a service, but you could get it from your root component. Something like this:

@Component {
  selector: 'dynamic-component',
  ....
}

export class DynamicComponent{
@Input selectedcomponent : string;

}

Then use it in a template:

<dynamic-component [selectedcomponent]="person"></dynamic-component>

And instead of using a service, switch on "selectedcomponent".

like image 88
Derek Kite Avatar answered Oct 21 '22 04:10

Derek Kite


The Answer is simply You Can't !!

While defining your component you must have to declare name of that component(i.e selector property) as well as class name. without declaring component name you can't create component.

so in your case there are option is either you create no. of components and call whenever you need of that component or create dynamic input value of that component so as per need set your dynamic value and get usng @Input. because for each component there is diff. template and logic as well, so better is to create new components and use as per need.

yes no doubt you can set dynamically data to that component like ID's ,name, custom input etc etc. hope it clears everything if not comment here !

like image 30
Pardeep Jain Avatar answered Oct 21 '22 04:10

Pardeep Jain


You cannot dynamically assign names to components the way you try to do it. However, you can dynamically assign ids to your elements with [attr.id]="id_string_expression" Most likely you can solve your problem that way. Something like:

<my-component [attr.id]="name+number" [data]="data" [anotherData]="anotherData"></my-component>
like image 1
hholtij Avatar answered Oct 21 '22 05:10

hholtij