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) ;
    }

}
2
  • How do you show this.text in template? Commented Jun 14, 2017 at 10:03
  • I updated the answer. Check it now Commented Jun 14, 2017 at 11:38

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

Error: Cannot find name 'myAlert' If i set this.myAlert() emulator is hangs
how about '<a (click)="'+this.myAlert()+'">Show allert</a>' ?
if (click)="'+this.myAlert()+'" then function cyclically runing on page init

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.