olivier
olivier

Reputation: 2645

Bind a click function to innerhtml with ionic

I would like to link to other ionic pages with [innerHtml].

For example i want to pass the following code to the app with [innerHtml]:

<a (click)="goto('10')">Ipsum</a>

I know that this wont work because security. But how else can i generate dynamic code with ionic and angular 4?

Could you show me an example what options I have?

It's a hacky app i use google sheets as backend.

Upvotes: 2

Views: 3242

Answers (2)

Martin Chuka
Martin Chuka

Reputation: 109

In case of anyone else with the same issue

you can run your angular 4 goto function using [innerHTML]

<a class="next-page" data-id="10">Ipsum</a>

and then call attachNextPageListener on ngAfterViewInit()

   private attachNextPageListener(){
    const pageElements=document.getElementsByClassName('next-page');
    if(pageElements && pageElements.length){
      for(let i=0; i<pageElements.length; i++){
        const goto=pageElements[i].getAttribute('data-id');
        pageElements[i].addEventListener('click',()=>{
          this.goto(goto);
          // run your angular code here with goto
        });
      }
    }
  }

then finally to allow the data-id, you can make a pipe with bypassSecurityTrustHtml or use it like Ondra answer.

Upvotes: 4

Ondra Koupil
Ondra Koupil

Reputation: 1073

You can bind a string to element's [innerHtml]. Angular will sanitize the code and remove any potentially unsafe parts. If it does so, a message will be logged to console.

<div [innerHtml]="someHtmlCode"></div>

If the code gets oversanitized and Angular clears some part that you want to keep, then you have to explicitly mark it as 'potentially unsafe', letting Angular know that you are aware of potential risks. Use DomSanitizer class' bypassSecurityTrust*() methods.

// component.ts
constructor(private sanitizer: DomSanitizer) {
}

public getHtmlWithBypassedSecurity(code: string): SafeHtml {
    return this.sanitizer.bypassSecurityTrustHtml(code);
}    

// component.html
<div [innerHTML]="getHtmlWithBypassedSecurity(someHtmlCode)"></div>

Upvotes: 1

Related Questions