2

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>
1
  • please create a stackblitz for button click problem and share it. Commented Feb 3, 2020 at 7:00

2 Answers 2

3

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>');
}
Sign up to request clarification or add additional context in comments.

1 Comment

the click function inside sanitised dom is not being parsed by angular
2

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!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.