Angular 2: Dynamic URLs for Templates

I am trying to switch between two different sidebars based on a variable obtained from the URL. However, when I attempt to implement this feature, I encounter an error message.

@Component({
    selector: 'sidebar',
    templateUrl: './sidebar.component.html',
    styleUrls: [
        './sidebar.component.css'
    ]
})

Here is my current implementation:

import {
  Compiler, Component, Injector, VERSION, ViewChild, NgModule, NgModuleRef,
  ViewContainerRef, AfterViewInit, OnInit
} from '@angular/core';
@Component({
    selector: 'sidebar',
    templateUrl: '<ng-container #dynamicTemplate></ng-container>',
    styleUrls: [
        './sidebar.component.css'
    ]
})

export class SidebarComponent implements OnInit {
@ViewChild('dynamicTemplate', {read: ViewContainerRef}) dynamicTemplate;
constructor(
private _compiler: Compiler,
        private _injector: Injector,
        private _m: NgModuleRef<any>
) {}
ngAfterViewInit() {
        let myTemplateUrl = './sidebar.component.html';

        if (this.modee === 'char') {
            myTemplateUrl = './Othersidebar.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);
            });
    }

However, upon testing this code, I receive the following error message:

client?afea:119 ..../app/sidebar.component.ts
Module not found: Error: Can't resolve './<ng-container #dynamicTemplate></ng-container>' in '.....\app\sidebar'
 @ ./src/main/webapp/app/layouts/sidebar/sidebar.component.ts 303:18-77
 @ ./src/main/webapp/app/layouts/index.ts
 @ ./src/main/webapp/app/app.module.ts
 @ ./src/main/webapp/app/app.main.ts
 @ multi (webpack)-dev-server/client?http://localhost:9060 webpack/hot/dev-server ./src/main/webapp/app/app.main

Can anyone provide a solution to this issue and explain what may be causing this error? Thank you.

Answer №1

i came across a possible fix:

templateUrl: '<ng-container #dynamicTemplate></ng-container>',

modify templateUrl to just template

unfortunately, it did not have the desired outcome

Answer №2

Ever considered implementing a router guard in conjunction with the sidebar template, allowing for dynamic switching based on route or URL? Imagine having a Sidebar Module featuring two distinct sidebars and corresponding routes for each: Template1 and Template2.

Just throwing in my own thoughts.

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

Developing a common module for use across deferred loading paths

I have been working on developing an Angular 11 application and am currently in the process of creating a SharedModule. My goal is to prevent loading common modules repeatedly across my lazy loaded routes. To achieve this, I created a shared module and imp ...

Confirmation of successful form submission

I have created a form to collect user details. Once the form is submitted, the page reloads. I am looking to show a success message after the page reloads. <form name="myForm" class="contactus-template" method="post" onsubm ...

Are all regular expressions in JavaScript compatible with the .NET framework?

Attempting to grasp the nuances between regular expressions in JavaScript and .NET. After perusing a few articles on the subject, Differences between C# and JavaScript Regular Expressions? https://www.codeproject.com/Questions/626385/Regex-pattern-for-csh ...

"Safari (iOS) is experiencing a functionality issue where Alert() is working, but console.log() is

Just a heads up before you dive in: I've encountered an issue with Safari related to Chrome, but it seems to work fine on other browsers. So, it could be more OS-specific rather than a general problem. I recently ran into a frustrating situation whil ...

How can I update the state with the value of a grouped TextField in React?

Currently working on a website using React, I have created a component with grouped Textfields. However, I am facing difficulty in setting the value of these Textfields to the state object. The required format for the state should be: state:{products:[{},{ ...

Is your URL getting cut off in jQuery?

How can I properly display a URL in an HTML table without it getting truncated? I'm attempting to show it within a table using jQuery, but it seems to be cutting off the URL. Here's a snippet of my code. Any suggestions on how to fix this? <! ...

Retrieving and updating the attribute value for d3.symbolTriangle

Currently, I am utilizing d3.symbolTriangle to create equilateral triangles in my project. I am interested in learning how to access and modify the attribute values. This is a snippet of my code: var body = d3.select("body"); var triangle = d3.symbol() ...

Error! D3.js is throwing an Uncaught TypeError because it cannot find the function .enter(...).append(...).merge

Currently, I am facing an issue while attempting to construct a table with multiple nested dropdowns using d3.js. The problem arises when switching from a newer version of d3 where my code functions flawlessly to d3.js v3. Upon replacing the newer version ...

Focusing on particular jQuery elements that share the same class names

I am facing an issue with dynamically generated divs that share the same class names. When I hover over the parent div (myDiv), I want to trigger an event and add a class to the myDiv child button. However, when I click on the parent div, I want to unbind ...

Tips for Integrating a Facebook Shop Page into Your Website

Can a Facebook shop page be integrated into a website? Any guidance on how to accomplish this task would be greatly valued. ...

What are some techniques for reducing the number of pages in my Carousel?

I need help figuring out how to set a limit of noOfPages for the number of pages per carousel. The functions in my code below don't implement this and I'm unsure how to do it. const itemsPerPage = 6; const [page, setPage] = React.useState(1); ...

What are the steps to create a DIV table after submitting a form?

I'm having trouble creating a header row for a DIV table using JavaScript (without jQuery). Instead of getting the expected output, I'm getting a row with the array items as headings separated by commas. https://i.sstatic.net/8O5QR.png var ma ...

Unexpected issue: Ajax sending empty values to populate SQL table using POST method

Attempting to input data from form fields into an SQL table using Ajax, encountering a problem. The Ajax request seems to be functioning correctly, but it is not capturing the values of the inputs before inserting a new row into the SQL table. The new row ...

Struggling to dynamically resize 2 boxes using JavaScript

I am attempting to create a layout with two Divs side by side, each containing slightly different content. I have successfully resized them equally using JavaScript, but the issue arises when loading the collapsed content as it does not adjust to the new s ...

Troubles arising from JavaScript functions within vue-router

I have implemented a function to authorize users, enabling restrictions on specific components based on their permissions. The function currently works effectively with the 'beforeEnter' navigation guard in Vue Router. However, I am facing diffic ...

Connect this - initiate the removal of an item

I am seeking assistance from more experienced colleagues to help me understand the code below and implement it in my App. The main objective is to trigger a REDUX action from a button, which will delete an item from a database. Here is the code that curr ...

Sorting JSON content to obtain particular outcomes

I am utilizing the Quotes on Design API https://quotesondesign.com/api-v4-0/ to display random quotes by various designers on my website. However, I am looking to showcase quotes by specific designers in a random manner. Unfortunately, the code snippet ...

Tips for wrapping text labels in mat-slide-toggles (Angular Material)

Is there a way to get the title in mat-slide-toggle to wrap if it's too long while keeping its default position to the right of the toggle? <mat-slide-toggle class="slider">A really long title wrapped</mat-slide-toggle> I attemp ...

The back button fails to refresh the page on a website utilizing Ajax technology

Recently, I implemented AJAX on a client's website to introduce some smooth animations for page transitions. When navigating from the homepage of firedogcreative.com to the edit page, and then to one of the work pages, we see a history like this: fir ...

What is the best way to input information into an object?

I am having an issue where I am trying to add data into an object, but I keep getting the error "push is not a function". Here is the object in question: var item = { "_id": { "$oid": "asdf976" }, "Categories": [{ "mainmodels": [{ "su ...