Angular 2: Triggering functions on click within a dynamic template (dynamic component)

Here is an example to demonstrate how to create dynamic templates and compile dynamic components in Angular 2.0:

How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

I have built my own template generator that fetches HTML content directly from a variable. You can find the generator here: http://plnkr.co/edit/2Sv1vp?p=preview

My question now is, how can I make the template content interact with the component, such as executing a function on click event?

Below is my app.component.ts code:

import { Component }          from '@angular/core';

@Component({
  selector: 'my-app',  
  template: `
    <div>
      <h2>An app with DYNAMIC content</h2>
      <hr />
      <dynamic-detail [tmpl]="tmpl1" [entity]="entity"></dynamic-detail>
      <dynamic-detail [tmpl]="tmpl2" [entity]="entity"></dynamic-detail>
    </div>`,
   })
   export class AppComponent { 
     private tmpl: string;
     private entity: any;

     constructor() {
       this.entity = { 
         code: "ABC123",
         description: "A description of this Entity",
         name: "Bea"
       };

       this.tmpl1 = '<h2>I am {{entity.name}}, the first template</h2>';
       this.tmpl2 = '<a (click)="printSomething()">I am the second template</a>';
      }

    printSomething() {
      console.log("Hello World");
    }
}

When I try to click on "I am the second template", it should execute the printSomething() function, but instead I get this error:

 Error in ./CustomDynamicComponent class CustomDynamicComponent - inline template:0:0 caused by: self.context.printSomething is not a function

Answer №1

The issue arises from Angular's message indicating that the 'printSomething' function does not exist in your dynamically created component. By declaring a function within the dynamically created component, you can successfully call it:

app.component.ts

this.tmpl2 = '<a (click)="linkClicked()">I am the second template</a>';

type.builder.ts

  protected createNewComponent(tmpl: string) {
    @Component({
      selector: 'dynamic-component',
      template: tmpl,
    })
    class CustomDynamicComponent implements IHaveDynamicData {
      @Input() public entity: any;

      linkClicked() {
        console.log('yay!');
      }

    };
    // a component for this specific template
    return CustomDynamicComponent;
  }

If you wish to invoke a method in app.component.ts, you will need to pass a reference to it using a new @Input() attribute of CustomDynamicComponent.

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

Unable to allocate information in the subscribe method

I'm experiencing an issue with the post method. Whenever I try to retrieve data using the segmentService, I always receive an empty segmentdata object in my temporarySegment variable. Strangely enough, when I use the same approach for retrieving numbe ...

What is the reason behind the triggering of actions by ngrx entity selectors?

I'm currently in the process of learning NgRx, but I'm struggling to comprehend why entity selectors would trigger actions. Despite my efforts to find an explanation, I have come up short. It's possible that I may be missing some fundamental ...

Starting PM2 with multiple instances can be achieved by following these steps

While running my nodejs code with PM2, I encountered a requirement for multiple instances of nodejs executing the same code. To address this need, I created a script named "myscript.sh": cd ~/myproject PM2_HOME='.pm2_1' /usr/local/bin/node /u ...

guide on implementing optional URL parameters in NestJS

Currently, I am in the process of transitioning to the Nestjs library for our backend service. I am looking to create a route that includes 2 optional parameters in the URL. Here's what I have in mind: /route/:param1/config/:OptionalParam3?/:Optional ...

Create a new project using Firebase Functions along with a Node.js backend and a React.js frontend

In the process of developing my application, I have chosen to utilize node.js, express.js, and Firebase with firebase functions, all coded in TypeScript. For the client side framework, I am interested in incorporating react.js. Currently, I have set up nod ...

A guide on implementing a universal service to seamlessly incorporate jQuery datatable across all pages in an Angular application

I am looking to streamline the process of integrating jQuery datatables with export buttons across multiple pages. After installing jQuery and typings for jQuery, I made sure to include jQuery in the types array of tsconfig as well. "types": [ "jquery" ...

Guide on building a basic cache system with RxJs

I am interested in developing a caching service using RxJs. The concept is quite simple - I have a class that retrieves initial data from a server and a websocket that sends notifications to this service regarding additions, edits, or deletions of entities ...

Trouble displaying data with Angular 6 JSON object pipe

Having an issue with displaying tasks from a MongoDB project schema in HTML. The tasks are stored in a nested array and I want to show the task name and description. Here's the code: <div class="card-body"> {{project.taskName | json}} </ ...

How can I retrieve error details specific to the line numbers of TypeScript files in a Node.js environment?

In my node.js backend development, I rely on TypeScript. One issue I often face is that when errors occur in node.js, it displays the line numbers from the transpiled JavaScript (.js) files rather than the original TypeScript (.ts) files. However, in proj ...

Issue: AuthInterceptor Provider Not Found

I've been attempting to set up an http interceptor with the new HttpClient in Angular 4.3, but I'm continuously encountering this error message: ERROR Error: Uncaught (in promise): Error: No provider for AuthInterceptor! In my app.module.ts f ...

Combining and mapping arrays in Javascript to form a single object

I am using the following firebase function this.sensorService.getTest() .snapshotChanges() .pipe( map(actions => actions.map(a => ({ [a.payload.key]: a.payload.val() }))) ).subscribe(sensors => { ...

Only filter the array by its value if the value is specified

Is there a way to apply this filter while only checking each condition if the value is not undefined? For instance, if taxId is undefined, I would like to skip it rather than using it as a filter criterion. this.subAgencies = demoSubAgencies.filter(fun ...

Establish a connection between a client and server by utilizing Python and TypeScript to link two sockets

Challenge I'm currently facing difficulty in establishing a connection between two sockets, specifically in the client-server relationship (single connection). Current Setup I have successfully set up my server using python3 and have also hosted my ...

Is ngClass failing to activate a class upon clicking?

I am having trouble displaying the activated class as active. It briefly switches to that class and then reverts back. Here is what I have tried: <ion-row > <ion-col col-3 (click)="deviceType('Light')" ><div class="c ...

Retrieve the raw text from the input field instead of the date object

Below is the HTML code for an input field: <div class="input-group input-group-md"> <input id="date" name="date" [readOnly]="disabled" type="text" placeholder="M0/d0/0000 Hh:m0:s0" [placeholder]="pl ...

Troubleshooting: Fullscreen Video Autoplay Issue in Angular HTML

Could someone shed some light on why this autoplay video isn't working properly in Chrome? The video is actually hosted in firebase storage. Interestingly, it plays fine when you navigate to a different page and then return to the homepage, but doesn ...

Ways to determine the presence of a route in Angular2

How can I determine if a route exists in Angular2? I have a function that stores the route to navigate to if the user is unauthorized. Upon logging in, I use: this.router.navigate([this.authService.redirectUrl]); However, I only want to navigate IF the ...

The items are not displayed in the app.component.html file

I am having trouble displaying the product list in an HTML file. Despite receiving the product data in a JavaScript message, it is not showing up when I try to list it in the HTML. Can anyone assist me in resolving this issue? Below is the code snippet: im ...

What are the steps to locally test my custom UI library package built with tsdx in a React.js project

I am currently utilizing tsdx to develop a React UI library, and I am looking to test it within my Next.js project before officially publishing it to the npm package. Initially, I attempted using npm link, which worked initially. However, when I made ch ...

Writing a condition using *ngFor to validate two values

I am currently utilizing angular 7. Within my Component, I have a Stock Array as displayed below: private stocks:any = []; [{ "scripcode": "M&M", "open": "671.95", "high": "676.90", "low": "661.60", "exchange ...