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

Jest's --findRelatedTests fails to identify associated test cases

Whenever I execute the command jest --bail --findRelatedTests src/components/BannerSet/BannerSet.tsx , an unexpected message is displayed: I couldn't locate any tests and hence exiting with code 1 If you want to exit with code 0 even when there are n ...

Exploring the potential of Angular2's WebSocket service by efficiently accessing the parent component

I need some assistance with implementing WebSockets in my angular2 application. However, I've encountered a minor issue that I can't seem to solve. Here's what I have so far: I've created a service that has a method for creating a WebS ...

Utilizing RxJS finalize in Angular to control the frequency of user clicks

Can someone provide guidance on using rxjs finalized in angular to prevent users from clicking the save button multiple times and sending multiple requests? When a button click triggers a call in our form, some users still tend to double-click, leading to ...

Utilize Angular 9 to fetch data from an API using the Get method, map them to a class, and

Seeking to extract information from a test URL and convert the data into a list, I aim to exhibit them in an alert/Loop for testing purposes. The dummy API URL being used is: The returned data follows this structure: {"status":"success","data":[{"id":"1" ...

What is causing the element to disappear in this basic Angular Material Sidenav component when using css border-radius? Check out the demo to see the issue in action

I have a question regarding the Angular Material Sidenav component. I noticed that in the code below, when I increase the border-radius property to a certain value, the element seems to disappear. <mat-drawer-container class="example-container" ...

How can I effectively filter the data returned by consuming an API in JSON through an Angular service?

My Angular 6 project includes a UsersService that is injected into the UsersComponent. Originally, the component displayed mock data in the form of a string array. However, it now consumes JSON data from an API provided by JSONPlaceholder via the UsersSer ...

Tips on Configuring the Attributes of a TypeScript Object in Angular 2

A TypeScript class called Atom is defined as follows: export class Atom { public text: String; public image: boolean; public equation: boolean; } To create an object of type Atom class and set its properties, the following steps are used: atom: ...

Enhancing UI-Grid: Implementing Dynamic Field Addition in the Header Name Section

There is a grid with a field named Users, and the requirement is to display the count of Users in the header name of a ui-grid. How can I achieve this? This snippet shows my JavaScript file code: var userCount = response.usercount; columnDefs: [{ nam ...

Attempting to access a specific JSON key using Observables

Apologies for the question, but I'm relatively new to Typescript and Ionic, and I find myself a bit lost on how to proceed. I have a JSON file containing 150 entries that follow a quite simple interface declaration: export interface ReverseWords { id ...

Transition from tslint to a new linter

Is it possible to remove tslint globally and switch to using eslint as the default in my Angular projects? When creating a new project with the command ng new myProj, I would like to have an eslint.json file instead of tslint.json. ...

The function of TypeScript map is not working properly

Encountering the error message "data.map is not a function" while trying to map data from a REST API request returning JSON data. It appears that the issue may stem from the data structure, as it seems like the returned data should be accessed with data.da ...

Troubleshooting the issue of "_this is undefined" in Angular 4

connect=()=>{ this.api=new trovaSDK_Init("normal",this.businessKey,"user","<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="364345534476515b575f5f1e19565d">[email protected]</a>","","","",this.apiCallBack,thi ...

What factors should I consider when determining whether to include @types/* in the `dependencies` or `devDependencies` section?

Currently using TypeScript 2 in my project, I am looking to incorporate a JavaScript library along with its typings. While I know I can easily install the types using npm install @types/some-library, I am uncertain whether to use --save or --save-dev. The ...

How can I activate a custom event on a repeated div element in Angular 2?

I am working on a project where I need to create multiple divs using an ngFor loop. When a user clicks on one of the divs, I want to add a unique class only to that specific div. Currently, I am using a boolean flag on [ngClass] as a test case, but I am u ...

Using a decorator with an abstract method

Discussing a specific class: export abstract class CanDeactivateComponent { abstract canLeavePage(): boolean; abstract onPageLeave(): void; @someDecorator abstract canDeactivateBeforeUnload(): boolean; } An error occurred stating that A decorat ...

Error: Unable to locate sportsRecord due to missing function

updated answer1: Greetings, I have updated the question with some detailed records and console logs for better understanding. sportsRecord = { playerTigers:[ {TigerNo: 237, TigerName: "Bird Bay Area", TigerkGroupNo: 1, isDefault: true ...

Leveraging the browser's built-in validation error messages in Angular for HTML forms

Is there a way to incorporate browser's native HTML validation error messages into Angular applications? What I am looking for is the ability to leverage the built-in error messages when working with reactive forms like this: testForm: FormGroup = th ...

flushMicrotasks does not function properly in conjunction with the image.onload event

Working on an Angular project, I'm currently developing an object with an image field. The method responsible for loading the image returns a promise that resolves in the onload function of the image. When trying to test this method using the flushMi ...

Enclose the type definition for a function from a third-party library

I prefer to utilize Typescript for ensuring immutability in my code. Unfortunately, many libraries do not type their exported function parameters as Readonly or DeepReadonly, even if they are not meant to be mutated. This commonly causes issues because a ...

"Navigate with ease using Material-UI's BottomNavigationItem and link

What is the best way to implement UI navigation using a React component? I am currently working with a <BottomNavigationItem /> component that renders as a <button>. How can I modify it to navigate to a specific URL? class FooterNavigation e ...