4

How i can run function from string in controller in Ionic 2. My code:

export class ProjectsPage {

    text:string = '' ;

    constructor() {
        this.text = '<a (click)="myAlert()">Show allert</a>' ;
    }

    myAlert() {
        alert(1) ;
    }

}
wstudiokiwi
  • 880
  • 1
  • 15
  • 33

2 Answers2

3

You can do this by using DomSanitizationService. Import the service

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

Now, in class constructor do this

  constructor(sanitizer: DomSanitizationService) {
      this.text = '<a (click)="myAlert()">Show allert</a>' ;
      this.text = sanitizer.bypassSecurityTrustHtml(this.text);
  }

Use like this in template

<div [innerHTML]="text"></div>  // here the DOM will be appended

Have a look at this answer to follow up the updates in the release versions and imports

Mr_Perfect
  • 8,254
  • 11
  • 35
  • 62
2

I can only guess what you are asking for, but your mistake is most likely caused by passing string in (click) function. Change is to:

 this.text = '<a (click)="'+this.myAlert()+'">Show allert</a>' ;

This should do the trick.

uksz
  • 18,239
  • 30
  • 94
  • 161