How to programmatically generate buttons with click functionality in Angular 2 and above

Is there a way to dynamically create a button in Angular using innerHtml? I have managed to create the button, but unfortunately, its click event is not functioning properly. Can anyone provide guidance on how to resolve this issue?

Below is my HTML code snippet:

<div  [innerHTML]="answerPanelContent"></div>

And here is my TypeScript code snippet:

 answerPanelContent: any;

   constructor(private sanitizer: DomSanitizer){

   }
ngOnInit() {
 this.answerPanelContent =  this.sanitizer.bypassSecurityTrustHtml(`<button type="button" class="btn btn-primary float-left"
                                           (click)="removeAnswer()" title="Remove Answer"
                                           aria-label="Close">
                                          Remove</button>`);

  }
    removeAnswer(){
      alert('Button clicked!');
    }

If you'd like to view a working example, check out the StackBlitz URL provided: https://stackblitz.com/edit/angular-nka4w9

Answer №1

I highly advise against using innerHTML in this situation. It is not intended for this purpose and does not align with the principles of Angular.

Utilizing *ngFor Directive

This approach is the recommended solution and follows the best practices of Angular.

component.ts

export class AppComponent  {
  public buttonTexts:Array<string> = ['First button'];

  public addButton(index:number):void {
    this.buttonTexts = [...this.buttonTexts, `button ${index}`];
  }
}

template.html

<button 
   *ngFor="let text of buttonTexts; let i = index;"
   (click)="addButton(i)">{{text}}</button>

Check out StackBlitz

Using Renderer2

Resort to this method only if *ngFor cannot address your specific requirements.

component.ts:

export class AppComponent implements AfterViewInit {
 
  @ViewChild('inserttarget', {static: false})
  public insertTarget:ElementRef; // utilize this for inserting into a particular element in your template

  constructor(
    private renderer:Renderer2, 
    private el:ElementRef // use this if you want to insert into the root of your template
  ) {

  }

  public ngAfterViewInit():void {
    this.addNewButton();
  }


  public addNewButton():void {
    const button = this.renderer.createElement('button');
    const buttonText = this.renderer.createText('Click me');

    this.renderer.appendChild(button, buttonText);
    this.renderer.appendChild(this.insertTarget.nativeElement, button); // employ this.el.nativeElement to insert into the root of the template
    this.renderer.listen(button, 'click', () => this.addNewButton());
  }
}

template.ts

<p #inserttarget>
  Some text
</p>

Here's a functional StackBlitz demonstration.

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 library in Angular2 with multiple routes: a step-by-step guide!

Having recently delved into Angular2, I find myself in need of building a reusable library to be utilized by multiple applications as an html tag. This library will consist of various pages such as search, create, edit, etc., each requiring different rout ...

An issue has occurred with the NullInjector, specifically regarding the AppModule and Storage in Ionic 4

When attempting to launch my Ionic app using npm start, an error message appears stating "NullInjectorError: No provider for Storage!". I have already included Storage in the app.module.ts file as shown below: imports: \[ BrowserModule, IonicModule ...

Defining onClick event in Typescript and React.Konva

Struggling with resolving the tslint error Type declaration of 'any' loses type-safety., particularly when it comes to determining the correct type for the Event. Currently converting the Lynda tutorial "Building and Deploying a Full-Stack React ...

Using the <template> syntax to apply ngclass or [class.classname]

I am familiar with the syntax for ngFor, ngIf, and ngSwitch using templates. Can someone provide guidance on how to utilize ngClass or [class.className] with template syntax in Angular 2? Can anyone explain how to implement classes using template syntax i ...

Ensure to pass the correct type to the useState function

I have a basic app structured like this import React, { useState } from 'react' import AddToList from './components/AddToList' import List from './components/List' export interface IProps{ name: string age: number url: ...

In TypeScript, the Select element does not contain an options property

Having trouble iterating through a TypeScript array. Here are the methods I'm using: getNotification(evt: string, rowIndex: number) { console.log("Production order: law has changed to " + evt + " " + rowIndex); var select = document.getEleme ...

Exploring the Use of Enums in AngularJS HTML Tags

One of my challenges involves using an Enum in typescript: enum EnumCountries{ Canada=0, USA=1, Holland=2 } When working in AngularJS, I encountered some difficulties incorporating it into the HTML. For example, this code snippet did not ...

The Angular 16: Karma Test Explorer is reporting an error stating that afterAll, there is an Uncaught ReferenceError, as it

Angular 16: Encountering an error while attempting to install or run the Karma Test Explorer within VSCode. The specific error message is as follows: Failed to load tests - Test discovery failed: Browser Error - An error was thrown in afterAll Uncaught Re ...

Unleashing the Power of Angular 2's Reactive Form Isolation Feature

I am new to reactive forms and I need help with isolating scope when using FormArray in Angular. In the code below, I have a room type where I can add or remove form groups. When I select a value for the room type in the drop-down, it should populate the c ...

Having trouble running tests on Angular service that has a Console constructor parameter

Attempting to incorporate a logging service in my project, the name service implies its purpose. During initialization, a specific implementation of the logging service is selected. This implementation utilizes the console for logging messages. Ensuring t ...

TypeScript versions 2.3 and 2.4 experiencing issues with generic overloads

After upgrading from typescript 2.2, I encountered an issue with the following example. interface ILayoutResult { id: string; data: any; } interface ILayout{ getResult<T extends ILayoutResult | ILayoutResult[] | void>() :T; } class te ...

Having trouble resolving the typescript package while integrating with another module

Attempting to develop a basic npm package with TypeScript and bundle it using webpack. When trying to use the package in another module, such as a react application named 'module A.' Within module A, the 'myLibrary' package is installe ...

Identifying the various types in Typescript

In the process of developing a solution for Excel involving data from an Office API, I encountered the challenge of distinguishing between different types that a function can return. Specifically, the data retrieved as a string may belong to either a "Cell ...

Angular Unit Test: Received 1 argument instead of the expected 3

Currently, I am in the process of unit testing an Angular application. This is my first time venturing into Angular Unit Testing. To save time, I downloaded the angular app from here. As a beginner in Unit Testing, I watched some informative videos on the ...

Troubleshooting problems with resolving deeply nested promises

My approach to utilizing promises has been effective until now. The issue arises when the console.log(this.recipe) returns undefined and console.log(JSON.stringify(recipes)) displays an empty array. This suggests that the nested promises may not be resolvi ...

Create a const assertion to combine all keys from an object into a union type

I am working with an object similar to this (demo link): const locations = { city: {name: 'New York'}, country: {name: 'United States'}, continent: {name: 'North America'} } as const My goal is to create a union t ...

Issues with Loading childComponent in Angular 5 Parent Component

How can I successfully load an internal component, specifically the store-top component at app/stores/store/store-top.component? I want to display the store-top content in the store component when a user clicks on any of the stores from a list. Any sugges ...

Using a single Angular component to dynamically load data based on the query string

I am curious if it is feasible to load data based on a query string. For instance, when the user clicks on the following link http://localhost:4200/earning/customers?type=archived, the data will be loaded using the same component CustomersComponent. Simila ...

A glitch was encountered during the execution of the ionic-app-scripts subprocess

I recently started using Ionic 3 and created an application that I'm trying to convert into an APK. To generate a debug (or testing) android-debug.apk file, I used the following CLI command: ionic cordova build android --prod The pages are declared ...

The JSX element 'Provider<AnyAction>' does not match a valid instance type. The render() function should return compatible types

https://i.sstatic.net/MBHo5.pngMy current provider error just started happening out of nowhere, even though everything was working fine yesterday. Any suggestions on how to troubleshoot and fix this issue? ReactDOM.render( <React.StrictMode> ...