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

What is the difference between *ngIf vs [hidden] What is the difference between *ngIf vs [hidden] ??

Câu trả lời

In Angular, both *ngIf and [hidden] are used to control the visibility of elements, but they do so in fundamentally different ways that can impact performance, behavior, and the structure of the Document Object Model (DOM).

*ngIf Directive

*ngIf is a structural directive in Angular, meaning it can add or remove elements from the DOM based on a specified condition. When the condition for *ngIf evaluates to false, Angular removes the element and its children completely from the DOM. This not only makes the element invisible but also unloads it from the browser's memory, which can be beneficial for performance if the element is not needed and is resource-intensive[1][2][3][4][5].

[hidden] Property

On the other hand, the [hidden] property is a simple HTML attribute that Angular manipulates to control element visibility. When an element is set with the [hidden] attribute, Angular applies a CSS style of display: none; to the element. This hides the element from view, but unlike *ngIf, the element remains in the DOM. It is not visible on the page, but it still exists in the document's structure and can be interacted with programmatically[1][2][3][4][5].

Key Differences

  1. DOM Presence:

    • *ngIf: Completely removes the element from the DOM when the condition is false. The element does not consume any resources or participate in DOM interactions.
    • [hidden]: Keeps the element in the DOM but hides it from view. The element can still be interacted with using JavaScript or other DOM methods.
  2. Performance:

    • *ngIf: Generally offers better performance for dynamic elements that do not need to be interacted with when not in use, as it reduces the memory footp...
junior

junior

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

middle

What is Angular Universal?

middle

What happens if you use