Click from HTML Ionic 2 Controller

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

export class ProjectsPage {

    text:string = '' ;

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

    myAlert() {
        alert(1) ;
    }

}

      

+3


source to share


2 answers


You can do this using DomSanitizationService

. Service import

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

      

Now, in the class constructor, do this

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

      



Use this template in your template

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

      

Have a look at this answer to keep track of release and import versions updates

+2


source


I can only guess what you are asking for, but your error is most likely caused by passing a string to a function (click)

. Edit:

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

      



This should do the trick.

+2


source







All Articles