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

What is the difference between Structural and Attribute directives in Angular?

Câu trả lời

In Angular, directives are classes that allow you to add custom behavior to elements in the Document Object Model (DOM). There are two primary types of directives: structural and attribute directives, each serving distinct purposes and functioning in different ways.

Structural Directives

Structural directives are used to manipulate the DOM's structure. They can add, remove, or manipulate elements based on certain conditions. These directives are powerful tools for dynamically altering the layout of your application's view. A key characteristic of structural directives is that they are prefixed with an asterisk (*) when applied in templates.

Examples of Structural Directives:

  • *ngIf: Conditionally includes or excludes an element from the DOM based on the truthiness of the expression provided.
  • *ngFor: Repeats a template for each item in a given iterable, effectively creating or destroying DOM elements dynamically.
  • *ngSwitch: Adds or removes DOM elements by comparing a value to possible matches defined with ngSwitchCase.

Structural directives can significantly alter the layout by adding or removing elements from the DOM[1][2][3][4][5].

Attribute Directives

Attribute directives, on the other hand, are used to change the appearance or behavior of elements and components. They do not alter the structure of the DOM but instead modify attributes, properties, and behaviors of existing elements.

Examples of Attribute Directives:

  • ngStyle: Allows you to dynamically change the style of an element using an expression that evaluates to a style map.
  • ngClass: Dynamically toggles CSS classes on an element based on an expression's truthiness.
  • Custom directives: Developers can create custom attribute directives to implement custom behaviors or interactions with DOM...
junior

junior

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

middle

Explain the difference between Constructor and ngOnInit

junior

How would you protect a component being activated through the router?

senior

What is Incremental DOM? How is it different from Virtual DOM?

Bình luận

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

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