Search code examples
angularionic-frameworkionic3innerhtml

Ionic3 - ionic element/component not working in innerHTML


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

Solution

  • 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>