0
const link = '<a href="javascript:void(0);" (click)="redirectToPage(store)" class="btn grey">' + displayText + '</a>';

When I am clicking on the button in the page than nothing happens. Where am I getting wrong? I am using angular 7.

redirectToPage(store){
alert('take me to store');
}
  • 1
    How do you use this param in html?
    can work for you
    – AlleXyS Sep 06 '19 at 07:33
  • 1
    can you post your template where you use the variable? – deelde Sep 06 '19 at 07:37
  • Modified the answer, Please check again – Adrita Sharma Sep 06 '19 at 07:58
  • 1
    Angular transpile to javaScript changing the name of the "functions", so you can not do it using this aproach. You can use renderer2 – Eliseo Sep 06 '19 at 08:13
  • Some interesting solution can also be found [here](https://stackoverflow.com/questions/48817261/click-event-not-work-in-innerhtml-string-angular-4/48817568). But maybe you should ask why your html is inside a string (there's some design problem here) – Cristian Traìna Sep 06 '19 at 08:17

1 Answers1

0

Try like this:

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

export class AppComponent {

  constructor(private sanitizer: DomSanitizer) {

    Window["AppComponent"] = this;
    this.link = this.sanitizer.bypassSecurityTrustHtml('<a href="javascript:void(0);" onClick="Window.AppComponent.redirectToPage(`store`)" class="btn grey">' + this.displayText + '</a>');
  }

  displayText:any = "ABC"
  link 

  redirectToPage(store) {
    alert('take me to store');
  }
}

See Stackbiltz Demo

Adrita Sharma
  • 19,704
  • 10
  • 55
  • 71