简体   繁体   中英

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}" ("

The Answer is simply You Can't !!

While defining your component you must have to declare name of that component(ie 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 !

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>
<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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM