When working on my Angular project (version 8), I encountered an issue where a list of static HTML content retrieved from a database is not rendering correctly in the parent HTML. Strangely, only the last div
with innerHTML
is being rendered correctly, while all the preceding divs with child HTML are jumbled and do not display properly. It seems like the styles of the child HTML elements are not being applied, except for the last one.
To render the HTML, I am using a sanitize HTML pipe for the `div`. The Angular component's onInit
function queries the database in a loop. Each API call returns HTML text that is then added to an array of strings. This HTML text represents PDF files converted to HTML, each with its own style tag.
I suspect that only the style of the last innerHTML element is being applied to all the preceding child innerHTML
elements, causing the content to appear jumbled. Any suggestions on how to solve this issue?
Below is the code snippet for rendering the HTML:
<div *ngFor="let qBank of tsqm.selectedQuestions; let i = index">
<div class="page">
<div [innerHTML]="questionDataFromHtml[i] | sanitizeHtml"></div>
</div>
</div>
Here is the Sanitize HTML pipe implementation:
@Pipe({ name: 'sanitizeHtml'})
export class SanitizeHtmlPipe implements PipeTransform {
constructor(private _sanitizer: DomSanitizer) { }
transform(value: string): SafeHtml {
return this._sanitizer.bypassSecurityTrustHtml(value);
}
}
And here is a simplified version of the component code:
ngOnInit(){
this.questionset = this.storage.get(quesId);
// Pseudo code
forEach(item in this.questionset){
this.getHTMLfromDB(item)
}
}
getHTMLfromDB(question: QuestionBank) {
this.Service.getQuestionHtmlFile(question.questionFilePath).subscribe(res => {
this.questionDataFromHtml.push(res.text());
question.questionData.questionDataFromHtml = res.text();
});
}
Images of correct and incorrect displays can be seen here:
Correct display - Question1 and Question2 are the same: Correct display
Incorrect display - Question1 and Question2 are different: Incorrect display
You can view the code on Stackblitz here: Stackblitz