Dynamic Naming of Angular 2 Components

What is the process for setting a dynamic name to an Angular 2 component?

Below is the code snippet from my template:

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

I want to define the componentName in my class like this:

component: string = 'component';

However, I am currently facing the following error:

Uncaught (in promise): Template parse errors:
Unexpected closing tag "{{component}" ("

Answer №1

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

In my application, I utilize this code to display different components based on a selection. The components are defined and displayed using a switch statement. The selection is retrieved from a service, but it can also be obtained from the root component. Here is an example of how you can achieve this:

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

export class DynamicComponent{
@Input selectedcomponent : string;

}

You can then use the selectedcomponent in your template like this:

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

Instead of relying on a service, you can switch on the value of "selectedcomponent" to dynamically display the desired component.

Answer №2

The solution is quite simple: It's Impossible !!

When developing your component, it is essential to specify the name of the component (i.e selector property) along with the class name. Without declaring the component name, you are unable to create the component.

In your scenario, you have two options: either create multiple components and call them when needed, or create dynamic input values for the component. This way, you can set your dynamic values as needed using @Input. Each component has its own unique template and logic, so it's advisable to create new components and use them based on your requirements.

You can certainly dynamically set data to the component such as IDs, names, custom inputs, and more. Hopefully, this explanation clarifies everything. If not, feel free to leave a comment!

Answer №3

Assigning dynamic names to components is not possible in the way you are attempting. However, you can achieve dynamic assignment of ids to your elements using [attr.id]="id_string_expression". This approach is likely to help you resolve your issue. Here's an example:

<my-component [attr.id]="name+number" [data]="data" [anotherData]="anotherData"></my-component>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Opt for the browser's scrolling feature instead of the grid-level scrolling in ag-grid

Currently, I'm utilizing ag-grid to display data on my website. However, I've encountered an issue where there are two scroll bars present - one at the grid level and another at the browser level. My goal is to only have the browser level scroll ...

Discover convenient debugging utilities tailored for Angular JS 1.5

Being a newbie in the world of Angular JS, I may have some simple questions about debugging tools specifically for Angular JS 1.5. ...

I am struggling to grasp the issues with the RxJS v6 migration

After upgrading to Angular 6, I neglected to install rxjs-compat. This resulted in changes needed in my code. import {Observable} from "rxjs/Observable"; was changed to import {Observable} from "rxjs"; and so forth. However, when running ng serve, I ...

Attempting to access jQuery from an external JavaScript file within the Ionic 5 framework

Currently, I am working on an Ionic app with Angular. I want to call my JavaScript function when the document is ready in the JS file, but I keep encountering an error. Here is my watch.page.html: <ion-content> <div class="videoContainer&qu ...

Issue with sending functions to other components in Angular

I'm currently facing an issue with passing functions to other objects in Angular. Specifically, I've developed a function generateTile(coords) that fills a tile to be used by leaflet. This function is located within a method in the MapComponent. ...

Employing async/await for efficient data retrieval

Attempting to utilize async-await in TypeScript Vue 3 to retrieve data, but encountering an issue where the function is already logging 'undefined' (or executing before the function call) private async exportDataOrder() { await this.getDataEx ...

Is it possible for me to reinstall npm in an Angular project as a solution?

I recently started working on an Angular 9 project and installed various libraries. However, I encountered some issues with ngx-gallery and Renderer2 which led me to make edits in files like core.d.ts within the node_module/angular/core directory. As a new ...

The Angular ResolveFn error states that the inject() function must be invoked within an injection context

As I attempted to phase out Angular's "Resolve" class implementation in favor of the "ResolveFn" functional implementation, I encountered a perplexing issue. I have a basic resolver that is preparing my data. I am facing an error that has left me puzz ...

Service error: The function of "method" is not valid

In one of my Angular 2 applications, I have a class that contains numerous methods for managing authentication. One particular method is responsible for handling errors thrown by the angular/http module. For example, if a response returns a status code o ...

Choose a specific date on a Materialize datepicker and set it as the selected date

I am currently developing an application using Materialize that includes two datepickers: $(document).ready(function(){ $('#outDate').datepicker({ format: 'dd-mm-yyyy' }); }); $(document).ready(function(){ $(&apos ...

p-calendar validator necessitated

Currently, there is no built-in validator for the p-calendar control in PrimeNG: <p-calendar formControlName="startDateControl" [minDate]="today" showIcon="true"></p-calendar> Are there any alternative solutions available? ...

Determining the type of a keyof T in Typescript

I am currently working on developing a reusable function that takes an observable and applies various operators to return another observable. One issue I am facing is getting the correct type for the value based on the use of the key. The code snippet bel ...

Tips for dynamically displaying images in both horizontal and vertical orientations

I would like to showcase images in the imageList. Here is what I want: AB CD How can this be achieved? It's not a matter of being even or odd Perhaps the list could look something like this: ABCDE FG I simply want a new row or display:block when ...

Angular 6 - detecting clicks outside of a menu

Currently, I am working on implementing a click event to close my aside menu. I have already created an example using jQuery, but I want to achieve the same result without using jQuery and without direct access to the 'menu' variable. Can someon ...

Displaying an image in AngularJS using Express: A step-by-step guide

Greetings! I am currently utilizing the angular-fullstack generator to build my web application. For uploading images, I opted for ng-file-upload. //server/picture.contoller.js exports.upload = function (req, res) { //Create Picture on db ...

Angular: How can the dropdown arrow in 'ng-select' be eliminated?

Is there a way to hide the dropdown arrow in an 'ng-select' element in Angular? <div class="col-md-6"> <ng-select id="selectServiceType" [items]="clientServiceTypes$ | async" pl ...

Utilizing Angular 2's *ngFor to conditionally wrap elements can be compared to organizing a layout with three columns in a Bootstrap row, then starting a

Currently I am facing a challenge with using *ngFor and it has me puzzled. My goal is to incorporate UIkit, but the same concept would apply to Bootstrap as well. <div *ngFor="let device of devices" > <div class="uk-child-width-expand@s uk-te ...

The assignment of `accessToken` is restricted in Mapbox-gl's typing

I'm currently utilizing the mapbox-gl library in conjunction with TypeScript. Moreover, I have successfully installed its type definitions that are sourced from the community using @types/mapbox-gl. However, when attempting to import and assign an acc ...

angular contains vulnerabilities of a moderate severity level

I am encountering an issue while trying to set up the json server for a web application I am developing using Angular. Can someone provide assistance in resolving this problem? The following dependencies are at risk due to vulnerable versions: node_m ...

Retrieve a specific JSON object by ID in an Angular Typescript observable

Below is a json string that contains both "stocks" and "contacts" data arrays. Depending on the request, I need to extract either the "stocks" or "contacts" data: [{ "id": "stocks", "name": "Stocks", "data": [ { "id": 1, "name": "Act ...