How to add Angular attributes to dynamically generated element with a function as the parameter ?
Last Updated :
28 Apr, 2025
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.
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;
}
}
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.
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;
}
}
HTML
<app-dynamic-element></app-dynamic-element>
Output:
Â
Similar Reads
How to set id attribute of an element dynamically using AngularJS ? In this article, we will see how to change the ID of any element dynamically using AngularJS, along with understanding its implementation through examples.Approach 1: In this approach, a function is called when the button is clicked, which changes the ID of the element to id-5. We are calling a func
3 min read
How to add input fields dynamically on button click in AngularJS ? The task is to add an input field on the page when the user clicks on the button using AngularJs. Steps: The required component for the operation is created (add-inputComponent). In that component, html file (add-input.component.html) required html is written. In that HTML, the main div for input fi
2 min read
How to Create Button Dynamically with Click Event in Angular ? The task is to create a button dynamically with a click event using AngularJS, i.e., whenever someone clicks on the button then a new button gets created. The easiest way to create a button in AngularJS is to use the ng-repeat directive. We can easily hook up a repeat logic inside a button click eve
2 min read
How to call a function on click event in Angular2 ? A Function is a set of statements that takes input, does some specific computation, and produces output. An on click event occurs when the user clicks on an element. In this article, we will see How to call a function on click event in Angular2, along with understanding the basic implementation thro
3 min read
How to set the input field value dynamically in AngularJS ? Given an input field and the task is to set the input field value dynamically with the help of AngularJS.Approach: A value is being set to the input field despite the user enter something or not. ng-click event is used to call a function that sets the value to 'This is GeeksForGeeks' with the help o
2 min read
Why is colspan not a known native attribute in Angular 2? In order to understand it, we need to have a clear in-depth knowledge between Document Object Model(DOM) and HyperText Markup Language(HTML).Basically, DOM is a model of objects and is a logical tree representation of the document whereas HTML is a markup language that we used to build web-pages.Eve
2 min read
How to use ngFor with index as value in Attribute in Angular ? NgFor is used as a structural directive that renders each element for the given collection each element can be displayed on the page. In this article, we will learn how to store the index value of ngFor in an attribute so I can utilize it. Creating Angular application & Module Installation Step
3 min read
What is the best way to conditionally apply attributes in AngularJS? In the AngularJS application, the best way to conditionally apply attributes to the elements mostly relies on the specific requirement and the actual nature of the attribute that we need to change. Mostly, considering the use cases, we can use the two common approaches for conditional attribute appl
6 min read
How to add Buttons without Submit the Form in Angular? In Angular, when adding buttons to a form, their default behavior on click is to submit the form itself. However, there are certain situations in which it is necessary to create buttons for forms that provide some sort of functionality or trigger custom logic without triggering the default form subm
5 min read
How to include a JavaScript File in Angular and call a Function from that Script ? In this article, we will learn how to include a JavaScript file in Angular and call a function, defined inside that file, from that script.In Angular, we can include JavaScript script files to import some features or utilize some external libraries or pieces of code, which can be a great asset while
3 min read