[Fixed] How can I generate DOM element dynamically with attribute / event binding in Angular?


I’m trying to create a component which is dependent on a configuration json file. It’s content is dynamic so I need to add the elements dynamically.

I have the following lines in my controller for example:

const item: HTMLElement = this.renderer.createElement('div');
this.renderer.addClass(item, 'item');

This will generate a simple div:

<div class="item"></div>

How can I generate it with attribute / event binding, so it could be something like this:

<div class="item" [style]="property1" (click)="functionName()"></div>


To be more specific, I’d like to generate this structure:

<div class="item">
    <div class="toggler" (click)="onTogglerClick(3)">accessories</div>

    <div class="menu" [style]="visibility[3]">
        <div class="item">face masks</div>
        <div class="item">beanies</div>
        <div class="item">embroidered beanies</div>
        <div class="item">bucket hats</div>
        <div class="item">caps</div>
        <div class="item">neck sleeves</div>
        <div class="item">socks</div>


How about *ngFor with JSON object.

It’s bit tricky to bind the events for dynamically created DIV.

<span *ngFor="let object of yourObject">
     <div class="{{object.class}}" [style]="object.property1" (click)="functionName(object)"> {{object.lable}} </div>

Happy Coding.. 🙂

Leave a Reply

(*) Required, Your email will not be published