Open In App

How to add Angular attributes to dynamically generated element with a function as the parameter ?

Last Updated : 30 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

AngularJS is a JavaScript-based framework. It can be used by adding it to an HTML page using a <script> tag. AngularJS helps in extending the HTML attributes with the help of Directives and binding of data to the HTML with expressions. An Angular Service is a broad category that consists of any value, function, or feature that an application needs. A service is a class with a narrow and well-defined purpose. In this article, we will see how to add Angular attributes to dynamically generated elements with a function as the parameter.

Steps to add an attribute to the dynamically generated element: The following steps will be followed to include the Angular attributes to the dynamically generated element with a function as the parameter, which is described below:

Step 1: Create a new Angular project and install the necessary dependencies

ng new gfg-app
cd gfg-app

Step 2: Create a new Angular component

ng generate component dynamic-element

This will create a new directory called “dynamic-element” in your project’s “src/app” directory, along with the necessary files for an Angular component.

Step 3: In the DynamicElementComponent class has a @ViewChild decorator that references the #container template variable, which is defined in the template.

@ViewChild('container', { static: true }) container?: ElementRef;
constructor(private elementRef: ElementRef) {}

Step 4: In the ngOnInit method, a new dynamic element is generated using the generateElement method, and various attributes and event listeners are added to it.

 ngOnInit() {
    const dynamicElement = this.generateElement('button', 'my-class', 'Click!');
    dynamicElement.setAttribute('data-test', 'my-test-value');
    dynamicElement.addEventListener('click', () => {
      alert('You clicked a Dynamic button!');
    });
    this.container?.nativeElement.appendChild(dynamicElement);
  }

  generateElement(type: string, className: string, innerText: string) {
    const element = document.createElement(type);
    element.classList.add(className);
    element.textContent = innerText;
    return element;
  }

Step 5: Finally, include the DynamicElementComponent in your application by adding it to the declarations array in your Angular module in app.module.ts:

import { NgModule } from '@angular/core';
import { BrowserModule } 
    from '@angular/platform-browser';
import { DynamicElementComponent } 
    from './dynamic-element.component';

@NgModule({
  declarations: [DynamicElementComponent],
  imports: [BrowserModule],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

Step 6: Add the following code to include the dynamic element component in your template HTML file:

<app-dynamic-element></app-dynamic-element>

Approach 1: In this approach, the Renderer2 service has been used to create and add the elements to the template as it ensures that the change detection mechanism is triggered and updates the view accordingly. Also, it can optimize the rendering performance.

Example 1: Below example demonstrates how to add an angular attribute to a dynamically generated element in Angular.

  • app.module.ts

Javascript




import { NgModule } from '@angular/core';
import { BrowserModule } 
    from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { DynamicElementComponent } 
    from './dynamic-element/dynamic-element.component';
  
@NgModule({
    declarations: [
        AppComponent,
        DynamicElementComponent
    ],
    imports: [
        BrowserModule,
        FormsModule,
    ],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule { }


  • dynamic-element.component.ts

Javascript




import { Component, ElementRef, Renderer2 } 
    from '@angular/core';
  
@Component({
    selector: 'app-dynamic-element',
    template: '<div id="container"></div>'
})
export class DynamicElementComponent {
    constructor(private elementRef: 
        ElementRef, private renderer: Renderer2) { }
  
    ngAfterViewInit() {
        const container = 
            this.elementRef.nativeElement.querySelector('#container');
        const dynamicElement = 
            this.generateElement('div', 'my-class', 'Click here!');
        this.renderer.setAttribute(dynamicElement, 
                                   'data-test'
                                   'my-test-value');
        dynamicElement.addEventListener('click', () => {
            alert('You just a clicked a dynamically created element!');
        });
        this.renderer.appendChild(container, dynamicElement);
    }
  
    generateElement(type: string, className: string, innerText: string) {
        const element = this.renderer.createElement(type);
        this.renderer.addClass(element, className);
        this.renderer.setProperty(element, 'textContent', innerText);
        return element;
    }
}


  • app.component.html

HTML




<app-dynamic-element></app-dynamic-element>


Output:

 

Approach 2: In this approach, ElementRef class is used to directly access the DOM element and manipulate it as it is more faster and flexible than using the Renderer2 service.

Example 2: This is another example that demonstrates how to add an angular attribute to a dynamically generated element in angular.

  • app.module.ts

Javascript




import { NgModule } from '@angular/core';
import { BrowserModule } 
    from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { DynamicElementComponent } 
    from './dynamic-element/dynamic-element.component';
  
@NgModule({
    declarations: [
        AppComponent,
        DynamicElementComponent
    ],
    imports: [
        BrowserModule,
        FormsModule,
    ],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule { }


  • dynamic-element.component.ts

Javascript




import { Component, ElementRef, ViewChild } 
    from '@angular/core';
  
@Component({
    selector: 'app-dynamic-element',
    template: '<div #container></div>'
})
export class DynamicElementComponent {
    @ViewChild('container', { static: true }) container?: ElementRef;
    constructor(private elementRef: ElementRef) { }
  
    ngOnInit() {
        const dynamicElement = 
            this.generateElement('button', 'my-class', 'Click!');
        dynamicElement.setAttribute('data-test', 'my-test-value');
        dynamicElement.addEventListener('click', () => {
            alert('You clicked a Dynamic button!');
        });
        this.container?.nativeElement.appendChild(dynamicElement);
    }
  
    generateElement(type: string, className: string, innerText: string) {
        const element = document.createElement(type);
        element.classList.add(className);
        element.textContent = innerText;
        return element;
    }
}


  • app.component.html

HTML




<app-dynamic-element></app-dynamic-element>


Output:

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads