How can I use a string variable in Angular 2 to create a dynamic template URL

 @Component({
  selector: 'bancaComponent',
  templateUrl: '{{str}}'
})
export class BancaComponent implements OnInit {
  str: String;
  constructor(private http: Http) { }
  ngOnInit(): void {
  this.str = "./file.component.html";
}

Any alternatives to achieve the same outcome? Thanks for your help :)

Answer №1

Here is a potential solution for your issue:

import
{
    Compiler, Component, Injector, ViewChild, NgModule, NgModuleRef,
    ViewContainerRef, AfterViewInit, OnInit
} from '@angular/core';

@Component({
    selector: 'bancaComponent',
    template: `<ng-container #dynamicTemplate></ng-container>`
    // or with a templateUrl
})
export class BancaComponent implements AfterViewInit, OnInit
{
    @ViewChild('dynamicTemplate', { read: ViewContainerRef }) dynamicTemplate;

    constructor(
        private _compiler: Compiler,
        private _injector: Injector,
        private _m: NgModuleRef<any>)
    {
    }

    ngAfterViewInit()
    {
        let myTemplateUrl = './file.component.html';

        if (MYCONDITION === MAEXPECTATION)
        {
            myTemplateUrl = './another-template.component.html';
        }

        const tmpCmp = Component({
            moduleId: module.id, templateUrl: myTemplateUrl
        })(class { });
        
        const tmpModule = NgModule({ declarations: [tmpCmp] })(class { });

        this._compiler.compileModuleAndAllComponentsAsync(tmpModule)
            .then((factories) =>
            {
                const f = factories.componentFactories[0];
                const cmpRef = f.create(this._injector, [], null, this._m);
                cmpRef.instance.name = 'dynamic';
                this.dynamicTemplate.insert(cmpRef.hostView);
            });
    }
}

Based on the topic discussed at Angular 2/4 component with dynamic template or templateUrl

For more information, visit the official source : https://angular.io/guide/dynamic-component-loader

Answer №2

Angular 13: Creating Dynamic Components

If you want to create multiple components with specific templates in Angular 13, you can dynamically load these components using the following approach:

@Component({
    selector: 'app',
    template: `<ng-template #dynamic></ng-template>`
})
export class AppComponent implements AfterContentInit
{
    @ViewChild('dynamic', { static: true, read: ViewContainerRef })
    public dynamicContainer: ViewContainerRef;

    ngAfterContentInit()
    {
        const myComponentInstance = this.dynamicContainer.createComponent(MyComponent);
    }
}

source

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

Challenges encountered when unit testing ngx-translate

0 I am encountering issues with unit testing while using the ngx-translate library. Despite adding a provider for TranslateService, the tests keep asking for more providers, creating an endless loop of dependencies. Specifically, I am trying to unit test ...

Issue with integrating Bootstrap into Angular 2

When attempting to link to the bootstrap.css file located in the node_modules folder within index.html, I encountered an error. The application's folder structure is as follows: ecommerce-app/node_modules ecommerce-app/src/app/index.html All attem ...

Angular element fails to display properly

I'm currently working on developing a website using Angular and creating a header component. To generate the necessary files, I used the command ng g c commons/header which creates the HTML, SCSS, TS, and .spec.ts files. I then made modifications to t ...

VS-Code is not a fan of accessors when targeting ES6

I can't seem to figure out this strange issue I'm having with VS-Code (1.13.1, MacOS). Every time I try to use a class getter or setter, I get the following error: [ts] Accessors are only available when targeting ECMAScript 5 and higher. The ...

Substitute a specific text within an array of strings using Angular 2

Currently, I am working with a string array that includes elements such as age, gender, and nationality. Specifically, I am interested in replacing the element "age" with "agexxxx". Do you know of any methods to accomplish this within an Angular framewor ...

Tips for prohibiting the use of "any" in TypeScript declarations and interfaces

I've set the "noImplicitAny": true, flag in tsconfig.json and "@typescript-eslint/no-explicit-any": 2, for eslint, but they aren't catching instances like type BadInterface { property: any } Is there a way to configure tsco ...

What could be causing this peculiar behavior in my React/TypeScript/MUI Dialog?

My React/TypeScript/MUI application has a dialog that displays multiple buttons. Each time a button is clicked, the dialog function adds the button value to a state array and removes it from the dialog. Although it seems to be working, there is an issue wh ...

Challenges Experienced by AoT in Live Operations

So in my project, I have various components and services included where necessary. To ensure their accessibility, I made sure to declare all the services as private within the constructor. Here's an example: constructor(private myService: MyService) ...

Troubleshooting error in Angular 5 with QuillJS: "Parchment issue - Quill unable to

I've been working with the primeng editor and everything seems fine with the editor itself. However, I've spent the last two days struggling to extend a standard block for a custom tag. The official documentation suggests using the quilljs API fo ...

Error Page Reappeared After Refresh

I have a backend Spring Boot Application and I am using Angular 2 Single Page Application for the frontend. When I navigate to a specific route, such as localhost:8080/getAccounts, and then refresh the page, I encounter the Whitelabel Error Page. However, ...

Error message: "Error encountered while building Next.js - ReferenceError: 'describe' is not defined"

I am facing difficulties achieving a successful next build without encountering the following error: > Build error occurred { ReferenceError: describe is not defined Although the dev server and tests execute smoothly, it appears that the jest global d ...

Are the frameworks Vue, Angular, and React known for

During a conversation, I came across an interesting viewpoint criticizing popular frameworks such as Angular, Vue, and React. It was argued that these frameworks have a significant disadvantage: apart from the API part that interacts with the server's ...

Create a drop-down menu that dynamically populates options based on the selection from another drop-down menu using Angular

I am in the process of creating a form with 2 select dropdowns - one for countries and one for their respective states. The goal is to have a list of countries displayed, and when a country is selected, the second dropdown is populated with its main states ...

Ways to redirect to a different page following a successful execution of a mutation in React-query

I am facing an issue where a memory leak warning appears when I redirect to another page after a mutation. Despite trying various methods, I have not been able to find a solution. The specific warning message is: Warning: Can't perform a React state ...

Mastering Props Typing in React Using TypeScript

Currently, I am faced with the task of defining the following: interface MyCompProps { someAttr: number } Instead of having to explicitly list all the aria-* attributes I need upfront, I would like to simply use aria- and other normal HTML attributes ...

What is the best way to create an array of strings that can include multiple elements from a set of strings?

Exploring different roles for authorization: ['admin', 'manager', 'user'] Is there a way to create a specific type, named Roles, which is essentially a string array ( string[] ) that is limited to only containing values from ...

Has the GridToolbarExport functionality in Material UI stopped working since the latest version update to 5.0.0-alpha.37?

I have created a custom toolbar for my Data Grid with the following layout: return ( <GridToolbarContainer> <GridToolbarColumnsButton /> <GridToolbarFilterButton /> <GridToolbarDensitySelector /> <Gr ...

Can we categorize various types by examining the characteristics of an object?

Is it feasible with TypeScript to deduce the result below from the given data: const data = { field1: {values: ['a', 'b', 'c']}, field2: {values: ['c', 'd', 'e'], multiple: true} } const fiel ...

Adjusting the quantity of items in the blueprintjs Suggest component

In my current project, I have developed a react app using the blueprintjs visual toolkit. However, I am facing an issue where the <Suggest> box is displaying all elements from the array, instead of just the first 10 as shown in the documentation. Bel ...

Encountering the "Error: data.map is not a function" issue within Next.js

I'm having trouble understanding why this first fetch call works perfectly: async function getData() { const res = await fetch('https://jsonplaceholder.typicode.com/todos') return res.json() } export default async function Home() { co ...