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

Creating a build task in Visual Studio Code with universal TypeScript compiler settings

Our project has the following structure: +-- views +-- viewXXX +-- ts ¦ +-- controller.ts ¦ +-- helper.ts ¦ +-- ... (*.ts) +-- viewXXX.ctrl.js // this is the desired output file +-- viewXXX.c ...

Why does FormGroup.Get() return null when there is a period in the name of the FormControl?

Issue: I am facing an issue with the formGroup I created using formbuilder. The problem arises when a control within the FormGroup contains a . in its name. When attempting to retrieve the formControl using the formGroup.get method, it returns null. Sampl ...

Tips for integrating material icons into your project

Having some trouble using Outlined material icons in my application. Struggling with the import process and can only access the normal filled icons instead of the outlined ones. I would like to incorporate outlined icons similar to those shown in this exam ...

How come the index variable doesn't show the index in *ngFor loop in Angular 2?

When working with ng-repeat in Angular 1 to display the index, this code is used: <div ng-repeat="car in cars"> <ul> <li>Index: {{$index+1}}</li> <li>Car Name:{{car.name}}</li> </ul> </div> However, w ...

When attempting to send an archiver file in NodeJS, the request may become unresponsive

In my NextJS application, I am facing the challenge of generating a large number of QR codes at once, like 300, 400, or even 500, and then packaging them into a zip file for users to download. The following code snippet demonstrates how I achieve this usin ...

Discovering JSON data in Angular 4

I am working with a JSON data format retrieved from (this.url) { "user": [ { "id": "1", "name": "root", "password": "root" }, { "id": "2", "name": "clienttest", ...

failure to render updated content after modification of variable

I am facing an issue with triggering a function in the component: componentA.ts html = 'hey'; this.onElementSelected(r => this.change()); public change() { console.log(this.html); if (this.html === 'hey&ap ...

Creating asynchronous JavaScript constructors using a static method called "create" presents challenges when dealing with TypeScript types

I've been diving into the world of asynchronous constructors and have successfully implemented them in JavaScript. However, I'm facing a challenge with TypeScript types. Here's how it should ideally work: const a: AnyClass = await AnyClass. ...

Authentication for file uploads in Angular 2 using Dropzone and passportjs

I am currently working on implementing authentication for an admin user using Express, Passport, and MySQL in a specific page. The authentication process works fine, but I am facing an issue with verifying whether the user is logged in while uploading file ...

Develop a FormGroup through the implementation of a reusable component structure

I am in need of creating multiple FormGroups with the same definition. To achieve this, I have set up a constant variable with the following structure: export const predefinedFormGroup = { 'field1': new FormControl(null, [Validators.required]) ...

Issues with loading Angular 4 Bootstrap JS post compiling

Utilizing normal bootstrap 3 within an Angular 4 application has been working well when compiling for development using ng serve. However, upon building the application with ng build, I encounter an issue where my bootstrap.js fails to load. Below are th ...

Is the Angular maxlength parameter causing issues with user input?

Previously, the old ng-maxlength="5" would trigger a field error but allow user input to continue. Now, with maxlength="5", it seems that input is being prevented altogether. I have novalidate on my form - could Angular be causing this? Should input be all ...

The upcoming development server will exclusively deliver HTML content without scripts or assets, mirroring the setup of the standard create-next-app template

In an attempt to recreate the problem I am facing, I decided to start by setting up a new Next.js app template folder using the command npx create-next-app (Version 13.1.6==latest, all default options, Node v18.14.0==LTS). However, when I try to run the pr ...

"Ionic Calendar 2 - The ultimate tool for organizing your

I am using a calendar in my Ionic app that retrieves events from a database through an API. var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://portalemme2.com.br/SaoJoseAPI/agenda', true); this.http.get('http://portalemme2.c ...

The ngModel in Angular 6 did not update the value within the app component

Currently, I am honing my skills in Angular and TypeScript but have encountered a minor issue. Below is the code snippet from my component.html <div> <input [(ngModel)]="mynumber"> N is now {{N}} // some content I want to do with ...

Is it possible to generate an array of strings from the keys of a type or interface?

Imagine a scenario where we have a type or interface defined as NumberLookupCriteria: type NumberLookupCriteria = { dialCode: string; phoneNumber: string; } or interface NumberLookupCriteria { dialCode: string; phoneNumber: string; } Is there a w ...

Avoiding loading certain images within an *ngFor loop

Is it possible to control the loading of images within an *ngFor loop in Angular? Load image with index X first Fire a function once all other images have loaded The goal is to prioritize the display of important images while optimizing bandwidth usage. ...

Angular 2 Release Candidate 6 form input pattern always fails to pass

How can I ensure that a required input in my form fails validation if there is no non-whitespace character present? Despite setting the pattern to [/S]+, the validation does not pass. Could I be missing an import or something else? My Template: <form ...

Utilizing TypeScript to perform typing operations on subsets of unions

A TypeScript library is being developed by me for algebraic data types (or other names they may go by), and I am facing challenges with the more complex typing aspects. The functionality of the algebraic data types is as follows: // Creating ADT instatiat ...

Leverage properties within the storybook component template

When utilizing a class component in a narrative, it allows you to transmit properties as arguments: const Template: Story<MyComponent> = (args) => ({ props: args, component: MyComponent, }) export const Default = Template.bind({}); export co ...