1

I am creating dynamic HTML in the component but the normal ionic style is not working.

In html :

<div [innerHTML]="testHtml"> </div>

In component(ts)

public testHtml = "<button color='secondary' ion-button>Default</button>";

I also tried to trust html using pipe but that make working inline style only:

In pipe:

this.sanitizer.bypassSecurityTrustHtml(html);
Khurshid Ansari
  • 4,638
  • 2
  • 33
  • 52

2 Answers2

3

This issue is the same as Ionic button showing 'ion-button' is not a known element

Since ionic is a framework on top of angular, angular is not able to parse the ionic custom elements nor apply the correct CSS to it because parsing happens before the innerHTML is added.

So on that note, I would suggest to not create elements within an innerHTML directive. Let the usage of the innerHTML stay with text formatting.

Angular is meant to put html elements in the html template (.html file or the template: property). Whatever you are doing that you want to create the html inside the innerHTML you can place it in the .html file like so and just place an [ngIf] directive to show or hide the element or perhaps use the [ngClass] directive to add a specific class to the element.

<div>
    <button [ngIf]="someTrueCondition; else showTheOtherElement" color='secondary' ion-button>Default</button>
    <ng-template #showTheotherElement>
        <button  color='primary' ion-button>Default</button>
    </ng-template>
</div>
Ian Preglo
  • 421
  • 2
  • 10
  • No, it is not same https://stackoverflow.com/questions/51544863/ionic-button-showing-ion-button-is-not-a-known-element. this is ion-button is not available in ionic3 but introduce in ionic4 – Khurshid Ansari Apr 30 '19 at 04:58
3

Angular sanitizes all the dynamically added HTML.

Solution was simple - Using a pipe

import { Pipe, PipeTransform } from '@angular/core'; import {DomSanitizer} from "@angular/platform-browser";

@Pipe({
  name: 'safeHtml',
})
export class SafeHtmlPipe implements PipeTransform {

  constructor(private sanitizer:DomSanitizer){}

  transform(html) {
    return this.sanitizer.bypassSecurityTrustHtml(html);
  }

}

And using innerHTML tag and add your pipe

<div [innerHTML]="question | safeHtml"></div>

Works here.