Random Angular template string that does not contain a templateRef

Could a string retrieved from an external resource, such as an http response, be passed as a dynamic template that binds to the component's instance without relying on TemplateRef?

Context: Consider having an AppComponent with at least one variable name, but lacking a predefined static template in the codebase. Instead, the HTML content will be fetched at runtime from an external source.

This template should be able to be injected and function like any normal template, with access to the name property.

httpClient.get('template').then(val=>{
// val: '<div> {{name}} </div>'
  this.template = val;
})

Answer №1

If you wish to achieve your desired outcome, it is imperative to compile the template. This process may introduce a level of complexity.

The code snippet for this scenario would resemble this:

@Component({
  selector: 'hello',
  template: '<div #container></div>',
})
export class HelloComponent implements AfterViewInit {
  @ViewChild('container', { read: ViewContainerRef, static: false })
  container: ViewContainerRef;

  constructor(private injector: Injector) {}

  ngAfterViewInit() {
    // Define the component using Component decorator.
    const component = Component({
      selector: 'test',
      template: '<div>This is the dynamic template. Test value: {{test}}</div>',
      styles: [':host {color: red}'],
    })(
      class {
        test = 'some value';
      }
    );

    // Define the module using NgModule decorator.
    const module = NgModule({ declarations: [component] })(class {});

    const componentRef = this.container.createComponent(component, {
      injector: this.injector,
      ngModuleRef: createNgModuleRef(module, this.injector),
    });
    setTimeout(() => (componentRef.instance.test = 'some other value'), 2000);
  }
}

View Live Demo on Stackblitz

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

Understanding Angular 2 Testing: The Ultimate Guide to Implementing Async Function Calls

What is the purpose of using the async function in the TestBed when testing Angular 2? Is there a specific scenario where it should be used? beforeEach(() => { TestBed.configureTestingModule({ declarations: [MyModule], ...

Issue with Ionic: The schema validation has encountered errors stating that the property 'class' is required for the data path ".builders['app-shell']"

After updating from Ionic4 to Ionic5 and attempting to run the Ionic app, I encountered a server error with the following message: [ng] Schema validation failed with the following errors: [ng] Data path ".builders['app-shell']" should have requi ...

Struggled with the implementation of a customized Angular filter pipe

I have recently developed a custom filter type to sort the notes-list in my application, with each note containing a 'title' and 'message'. Although there are no errors, I am facing issues as the pipe doesn't seem to be working pr ...

Encountering a Problem with TypeScript Decorators

I've been diving into TypeScript by working on TS-based Lit Elements and refactoring a small project of mine. However, I'm starting to feel frustrated because I can't seem to figure out what's wrong with this code. Even though it' ...

Does Vue.js have its own version of Angular's named templates feature?

Check out this snippet of Angular code: <ng-container *ngIf="someCondition; else spinner"> Show Data </ng-container> <ng-template #spinner> Show Spinner </ng-template> Do you know if there is a similar vue.js equ ...

Leveraging typegoose in a multitenant environment within the nestjs framework

I am looking to implement multitenancy functionality where each tenant will have its own database. Can Typegoose dynamically create connections for this purpose? ...

Tips for mocking Dependent Modules in Jasmine when dealing with a plethora of dependencies in Angular 9

Looking to create a unit test for a component within an Angular project. The main component has 5-6 dependencies and extends another class with around 7 additional dependencies. What is the most effective method to set up the TestBed for this component? ...

Tips on implementing zod schema types with remapped fields using the toZod method

I'm currently working on mapping a schema key to a different name in my database interface Country { isoCode: string, nameEn: string, nameDe: string, phone: string, bla: string } const CountryJson = { i ...

Transforming numbers into arrays in JavaScript/TypeScript for Angular 7

What is the best way to convert the number 10 into an array in JavaScript? expected output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] OR How can I transform the number 10 into the number of items within an array using JavaScript? ...

What is the best way to utilize yarn in order to install a GitHub package that utilizes TypeScript and has not yet been compiled?

After making modifications to an npm package and using yarn link <project name> locally, everything works perfectly. However, when pushing it to GitHub and trying to add it to the project with yarn add <repo url>#<branch> instead of yarn ...

Add the specified HTML tag to the existing document. An error has occurred: HierarchyRequestError - The action would result in an invalid node

During my testing of a React/TypeScript project using Jest + Enzyme, I encountered an issue when trying to append an HTML tag. The error occurred with the following unit test code: const htmlTag: HTMLElement = document.createElement('html'); htm ...

Switching from the HTTPS to HTTP scheme in Angular 2 HTTP Service

I encountered the following issue: While using my Angular service to retrieve data from a PHP script, the browser or Angular itself switches from HTTPS to HTTP. Since my site is loaded over HTTPS with HSTS, the AJAX request gets blocked as mixed content. ...

`Is there a way to manage date formats across all components using a single method in Angular?`

I need assistance with controlling the date format of dates displayed in different components using one typescript file. How can I achieve this? app.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', ...

What is the correct way to define functions within an object using Typescript in this situation?

Currently in the process of converting a JavaScript project to TypeScript, I encountered this error message (utilizing urql): A function whose declared type is neither 'void' nor 'any' must return a value. ts(2355) on line: playerCrea ...

Placeholder for Images in Next.js with Typescript

Recently, I've been exploring Next.js with TypeScript and trying to utilize the image component with the placeholder prop. Unfortunately, I keep encountering an error in my implementation. Take a look at my code below: import bgSell from '../../ ...

Stop the inheritance of static components in a feature module by protecting the router-outlet

I am in the process of dividing my app into multiple feature modules. Currently, I am using only the router-outlet inside a component within a feature module. However, this approach brings along all the static components such as the navbar and footer. How ...

What is causing the malfunction in this overloaded function signature?

Encountering an issue when attempting to declare an overloading function type with a full type signature in TypeScript. For example: // Full type signatures for functions type CreateElement = { (tag : 'a') : HTMLAnchorElement, (tag ...

Develop an interactive React sidebar with changing elements

I'm in the process of developing a sidebar for a project, with the goal of making it similar to tools like Confluence. This means that we need the ability to rearrange documents and create subdirectory structures by simply moving the documents, with ...

Is it possible to assign functions to each keystroke that does not correspond to a specific keybinding in Angular?

In Angular, there are events tied to keybindings or actions like (focus), (blur), (keydown), and more. You can bind specific keybinds to certain keys as well, such as (keydown.enter), (keydown.alt), etc. Is there a method to trigger an event only when it ...

Change the router outlet to the currently selected tab

We are in the process of conceptualizing a cutting-edge angular 7 application featuring material design (md-tabs) with multiple tabs. Our goal is to enable dynamic tab creation, with each tab representing the content of a specific route. The home page sh ...