1

I'm working on reactive forms in Angular 8. There is a requirement where I need to load the html from database and show it on page.

Based on the answers mentioned in the this link, I wrote the code. Angular HTML binding

in html page

 <div class="col-md-10" [innerHTML]="genericHtml | keepHtml"></div>

created a new pipe as follows

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

@Pipe({ name: 'keepHtml', pure: false })
export class EscapeHtmlPipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) {
  }

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

setting the variable like this in component class

getGlobalMessage(): void {
        this.setupService.getMessage(true).subscribe(
            (setupModel: SetupModel) => this.onSetupRetrieved(setupModel),
            (error: any) => this.errorMessage = <any>error
        );
    }

    onSetupRetrieved(setupModel: SetupModel): void {
        this.genericHtml = this.setupEdit.html_content; //--> setting the variable from db value here
        console.log(this.genericHtml);
    }

I also set the encapsulation in Componenet header on the class

@Component({
    selector: 'home',
    templateUrl: './home.component.html',
    encapsulation: ViewEncapsulation.None
})

This works fine for the first time.

ISSUE It works fine the first time but when I navigate to other page and comes back to this page again. the html from the database loads in the variable but I can't see it on the page. I can see the html in the console.

enter image description here

Nouman Bhatti
  • 1,341
  • 6
  • 28
  • 54
  • Could you provide full code of component class? Or show where you call getGlobalMessage? Mau be you choose incorrect place to handle loading of component? – TemaTre Dec 09 '19 at 04:53
  • I'm calling this function in constructor. also tried it in OnInit – Nouman Bhatti Dec 09 '19 at 04:58
  • I'm sure this gets called everytime I came back to this page bcz I can see the entry in console window of the browser – Nouman Bhatti Dec 09 '19 at 05:04
  • set `pure: true` like this `@Pipe({ name: 'keepHtml', pure: true })` and try again – Yash Rami Dec 09 '19 at 05:09
  • 1
    Tried your scenario, seems to be working just fine. Can you pinpoint if there difference between your and mine implementation? https://stackblitz.com/edit/angular-dwyfn4 – Plochie Dec 09 '19 at 05:20
  • you are right @Plochie, issue is somewhere else in the code. figured it out now – Nouman Bhatti Dec 09 '19 at 23:14
  • Does this answer your question? [Angular HTML binding](https://stackoverflow.com/questions/31548311/angular-html-binding) – Nouman Bhatti Dec 09 '19 at 23:18

0 Answers0