Vishal Upadhyay
Vishal Upadhyay

Reputation: 63

Dynamic HTML In Angular

I want to use dynamic button in html and on click of it I want to call a function in angular. I am using angular 7. Now i found solution like put button tag in angular statically . But I don't want to use that, because I will have multiple buttons, inputs , date picker , time picker dynamically. So please help me on this. I have been research on this from last 2 days but not getting a perfect solution. I have been use innerHtml as well . But its not working. I have used sanitizer , it show button now in html but its click function is not working. its not calling my function.

Statically its working but on dynamic its not working. Please check my code below.

<br><h4>Dynamic</h4><br>
<div contenteditable="true [innerHtml]="dyanmicHtmlString"></div><br>
<h4>Static</h4><br>
<button (click)="somefunction()">Static Button</button>

this.dyanmicHtmlString = '<button (click)="somefunction()">Dyanamic Button</button>

Upvotes: 2

Views: 3615

Answers (2)

BartoszTermena
BartoszTermena

Reputation: 1487

You can dynamically add event listener with Renderer2, like below:

app.component.html:

<br>
 <h4>Dynamic</h4><br><div  [innerHtml]="dyanmicHtmlString  | safe: 'html'">
 </div><br><h4>Static</h4>
<br><button (click)="somefunction()">Static Button</button>

ts:

   name = 'Listen';
   listenerFn:any;
   dyanmicHtmlString = '<button class="dynamic" >Dyanamic Button</button>'
    constructor(private renderer: Renderer2) {}

   somefunction(){
     console.log('e')
   }

   ngAfterViewInit(){
    this.listenerFn =  this.renderer.listen(document.querySelector('.dynamic'), ('click'), () =>{
       this.somefunction()
     })
   }

   ngOnDestroy() {
    if (this.listenerFn) {
      this.listenerFn();
    }
  }

https://stackblitz.com/edit/angular-2uckbb?file=src%2Fapp%2Fapp.component.html

Hope it helps!

Upvotes: 2

Angela Amarapala
Angela Amarapala

Reputation: 1052

You can use ViewChild to add dynamic content in this case,

@ViewChild('myDiv', {static: false}) myDiv :ElementRef;

this.myDiv.nativeElement.insertAdjacentHTML('beforeend', '<button (click)="somefunction()" >Dyanamic Button</button>');

Check this stackblitz for more.

Using DOM Sanitizer:

<h4>Dynamic</h4><br>
<div contenteditable="true" [innerHTML]="dyanmicHtmlString"></div><br>

import { DomSanitizer } from '@angular/platform-browser';


constructor(private sanitized: DomSanitizer) {}

ngOnInit() {
    this.dyanmicHtmlString = this.sanitized.bypassSecurityTrustHtml('<button (click)="somefunction()" >Dyanamic Button</button>');
}

Upvotes: 3

Related Questions