Angular: Bind event to dynamic created element

Angular: Bind event to dynamic created element

Today, I faced an issue in an angular project about how to replace the specific character from strings. So my requirement is like that I need to add an event whenever a date format will appear in a sentence. Date format will be like this ( DD-MM-YYYY, DD/MM/YYYY, DD.MM.YYYY ). So Before displaying to view I need to wrap the date format with anchor tag and add a click event. So I thought let's write an article for this so this will be helpful for someone who has the same kind of requirement. So Let's Start

First, add the below code in app.component.ts file here I used a static string for a demo this will come from API response and used the angular Renderer2 to manipulate the HTML.

import {
} from '@angular/core';

 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css'],
export class AppComponent implements OnInit, OnDestroy {
 input =
 '<div>Please fill up this document by 10.10.2020. <br></div><div>Last Date to fill the document 12/12/2020</div><div><br></div><div><br></div>';

 public removeEventListener: () => void;

 constructor(private renderer: Renderer2, private elementRef: ElementRef) {}

 public parseDate(str) {
 var m = str.match(/\d{2}([\/.-])\d{2}\1\d{4}/g);
 console.log(m, '<><><>');
 return m;

 public ngOnInit() {
 this.test = this.parseDate(this.input);

 this.test.forEach((element) => {
 this.input = this.input.replace(
 new RegExp('(' + element + ')'),
 '<a href="">$1</a>'
 // Solution for catching click events on anchors using Renderer2:
 this.removeEventListener = this.renderer.listen(
 (event) => {
 if (event.target instanceof HTMLAnchorElement) {
 // Your custom anchor click event handler

 public ngOnDestroy() {
 // Cleanup by removing the event listener on destroy

 public handleAnchorClick(event: Event) {
 // Prevent opening anchors the default way
 const anchor = event.target as HTMLAnchorElement;
 alert(`You are trying to navigate to ${anchor.text}`);

Next in app.content.html file add the below code.

<div [innerHTML]="input"></div>

Now just run your angular project and visit to see the code in action. It will wrap the date string in an anchor tag with a click event.

Stackblitz: Complete code reference with Demo

Related Articles