How to add Angular attributes to dynamically generated element with a function as the parameter ?
Last Updated :
24 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 dynamically get the content width of a div using AngularJS ?
In this article, we will see how to dynamically get the content width of a div using AngularJS, along with understanding its basic implementation through the examples. The content width of a div can dynamically get using clientWidth and scrollWidth properties depending upon the user's requirement. I
2 min read
How to Conditionally Add an Attribute for an Element in VueJS?
In VueJS, it's common to add attributes dynamically to HTML elements based on certain conditions. This allows for greater flexibility and control when rendering elements. Vue.js provides several ways to conditionally add or remove attributes depending on data, logic, or component state. we will expl
2 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 hide an HTML element via a button click in AngularJS ?
In this article, we will see how to use a toggle button feature to hide and display an element by button click in Angular. The toggle button is a user interface control that may be useful for situations when the user wants to switch between 2 states or conditions. For instance, in our smartphone, we
2 min read
How to communicate from parent component to the child component in Angular 9 ?
Angular makes the communication between components very easy. In this article, we will learn how to communicate from a parent component to the child component. Approach: Let's create two components: parent child In the parent component, declare the property that you want to receive in the child comp
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