The innerHTML inside Angular components appears scrambled, with only the final innerHTML rendering correctly

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

Answer №1

One problem arises when the css styling gets overridden, causing the final values to be applied instead.

To address this issue, it is recommended to use id or class attributes to apply styles to specific components.

I have made some modifications to your stackblitz example. Take a look here

In hello.component.ts file:

The text color has been set to red using the text-red id.

export class HelloComponent {
  @Input() name: string;
  
html1 =
    "<html><head><style>  #text-blue {color:blue;}</style></head><body><h2 id='text-blue'>Inner HTML1 in red</h2></body></html>";
  
html2 =
    "<html><head><style>  #text-red {color:red;}</style></head><body><h2 id='text-red'>Inner HTML2 in blue</h2></body></html>";
}

Answer №2

To resolve the problem, I implemented a solution that involved utilizing the iFrame tag along with the srcdoc attribute. Our backend service sends HTML content to our Angular application, which is then sanitized before being displayed within the iFrames.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular 6: Addressing the 'ExpressionChangedAfterItHasBeenCheckedError' in dynamic form validation with reactive form by adding and removing elements

When utilizing Angular 6 Reactive Form and dynamically adding and removing new validators, an error occurs: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'disabled: false'. Current ...

Load CSS styles once the HTML content has been generated by the PHP script

One way to dynamically add a section of HTML during page load is by making use of PHP in the index.php file: In your index.php file, you can include a section like this: <html> <head> <link href="css/style.css" rel="stylesheet"> ...

The textboxes are not displaying the floating numbers correctly

My issue involves 3 textareas with numbers displayed next to them. While I previously used a CSS table layout, it became inefficient when adding content between each row. I am puzzled as to why the second number, "2)", appears positioned next to the first ...

Obtain both the key and value from an Object using Angular 2 or later

I have a unique Object structure that looks like this: myCustomComponent.ts this.customDetails = this.newParameter.details; //the custom object details are: //{0: "uniqueInfo", // 5: "differentInfo"} The information stored in my ...

Welcome to the interactive homepage featuring multitouch authentication

I am looking to design a homepage that is interactive based on touch input. For instance, if the user uses 5 fingers to touch the screen, similar to the green circles in the image below, they will be redirected to a specific homepage. If they touch in a di ...

Looking for guidance on integrating Forms with VueX and script setup? Are you utilizing v-model in your implementation?

UPDATE: I'm contemplating whether or not to abandon VueX entirely due to its outdated status, with Pinia being the preferred choice nowadays. Can someone confirm this? https://stackblitz.com/edit/vue-script-setup-with-vuex-hmrk5d?file=src/store.ts ...

What is the best way to integrate model classes within an Angular module?

I have a few classes that I want to keep as plain bean/DTO classes. They are not meant to be display @component classes, @Pipe classes, or @Directive classes (at least, that's what I believe!). I am trying to bundle them into a module so that they ca ...

Verify the input in text fields and checkboxes using JavaScript

I'm in the process of creating a complete "validate-form" function, but there are still a couple of things missing: Ensuring that the Name field only allows alphabetical characters and white spaces Validating that at least one checkbox is selected, ...

Directing a webpage to a particular moment within that page

Is it possible to automatically redirect users to a new page at a specific time? I would like visitors to be redirected to a new site starting from 12:00AM on December 31st, without allowing them to access the current site after that time. Is there a way ...

What is the reason for hasChildNodes returning true when dealing with an Empty Node?

When the user clicks on purchase and the cart is empty, there should be an alert. However, it seems that no response is triggered. Upon running the program, an error message appears stating that it cannot read the property of addEventListener which is unde ...

The "ngx-phone-select" directive is not defined with the "exportAs" attribute

Having an issue with ngx-phone-select in the phone number field, receiving the error message "There is no directive with "exportAs" set to "ngx-phone-select" http://prntscr.com/hzbhfo This problem occurs in Angular 4.3 using ngx-phone-select version 1.0. ...

How can I use CSS to conceal the controls for an HTML5 video?

Seeking advice on how to hide and show controls on an HTML5 video section. I currently have a setup where clicking on the video div opens a modal that plays the video in a larger size. The code for opening the modal and playing the video is working fine. ...

Is it possible to upload files without using AJAX and instead through synchronous drag-and-drop functionality in the foreground?

Currently, my website has a standard <input type="file"> file upload feature that sends data to the backend upon form submission. I am looking to enhance the functionality of the form by allowing users to drag and drop files from anywhere within the ...

Generate a Calendar Table using JavaScript in the Document Object Model (DOM

I have set up a table with 6 rows and 5 columns. The purpose of the table is to represent each month, which may have varying numbers of days. I want each column to display dates ranging from 1-30 or 1-31, depending on the specific month. Here's what ...

What is the best way to enclose text within a border on a button?

I am trying to create a button with a colored border around its text. Here is the code for my button: <input id="btnexit" class="exitbutton" type="button" value="Exit" name="btnExit"></input> Although I have already added CSS styles for the ...

Utilizing Ionic with every Firebase observable

Can someone help me with looping through each object? I am trying to monitor changes in Firebase, and while it detects if there is a push from Firebase, I am facing issues displaying it in the HTML. Where am I going wrong? Thank you! ping-list.ts p ...

Hover to reveal stunning visuals

Can anyone help me figure out how to change the color of an image when hovered over using HTML or CSS? I have a set of social network icons that I want to incorporate into my website, and I'd like the icon colors to change when the mouse moves over th ...

Creating a form in PHP/HTML with a variety of selectable options

Here is my PHP and HTML code: $damt2 = isset($_POST['damt2']) ? $_POST['damt2'] : 200; $dateinfo2 = json_decode(file_get_contents($_SESSION['base_path'] . 'dl.dict'), true); arsort($dateinfo2); // Sort an array in r ...

Issue with the code flow causing nested function calls to not work as expected

I'm experiencing an issue with my code: The problem arises when param.qtamodificata is set to true, causing the code to return "undefined" due to asynchronous calls. However, everything works fine if params.qtamodificata is false. I am seeking a sol ...

The presence of parentheses in a JQuery selector

My database contains divs with ids that sometimes have parentheses in them. This is causing issues with my JQuery selector. How can I resolve this problem? Let me provide an example to illustrate: https://jsfiddle.net/2uL7s3ts/1/ var element = 'hel ...