Câu hỏi phỏng vấn Angular
Câu hỏi

You have an HTML response I want to display. How do I do that?

Câu trả lời

To display an HTML response in an Angular application, you can use the [innerHTML] property binding, which allows you to bind a template expression to the innerHTML property of an HTML element. This method is particularly useful when you want to render HTML content dynamically, such as content fetched from an API. Here’s how you can do it:

Step-by-Step Guide

  1. Fetch the HTML Content: First, you need to fetch the HTML content. This might come from an API or other data source. For example, using Angular's HttpClient module:

    import { HttpClient } from '@angular/common/http';
    import { Component, OnInit } from '@angular/core';
    
    @Component({
      selector: 'app-html-render',
      templateUrl: './html-render.component.html',
      styleUrls: ['./html-render.component.css']
    })
    export class HtmlRenderComponent implements OnInit {
      htmlContent: string;
    
      constructor(private http: HttpClient) {}
    
      ngOnInit(): void {
        this.http.get('api/endpoint', { responseType: 'text' })
          .subscribe(data => {
            this.htmlContent = data;
          });
      }
    }

    In this example, replace 'api/endpoint' with the URL of your API. The { responseType: 'text' } option tells HttpClient to treat the response as plain text, which is necessary for HTML content.

  2. Bind the HTML Content to an Element: In your component's template, use the [innerHTML] binding to assign the fetched HTML content to an element:

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

    This will render the HTML content within the <div> element.

Security Considerations

When using [innerHTML] to insert HTML dynamically, you must be cautious of Cross-Site Scripting (XSS) vulnerabilities. Angular tries to sanitize the HTML to make it safe, but it's crucial to ensure that the content does not include any potentially harmful scripts or tags.

  • Sanitization: Angular automatically sanitizes the HTML before inserting it into the DOM to prevent XSS attacks. However, if you trust the source of the HTML and need to include elements like <script> or <style>, you might need to bypass Angular's sanitization.

  • Bypassing Sanitization: If yo...

junior

junior

Gợi ý câu hỏi phỏng vấn

middle

What are Custom elements?

middle

What is difference between declarations , providers and import in NgModule?

expert

How would you extract webpack config from angular cli project?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào