ngSwitch is "Attribute Directive" OR "Structural Directive" ?

3261 views javascript

I am a bit confused regarding ngSwitch directive -- whether it is 'attribute directive' or 'structural directive'.

Attribute directives are written with 'square brackets' like [ngStyle], [ngClass], etc. (and we write it as [ngSwitch] which refers it as 'Attribute Directives').

Structural directives are written with 'aestrick' like *ngFor, *ngIf, etc. (and we write the cases as *ngSwitchCase="..." which means it is a structural directive).

<div [ngSwitch]="colorValue">
    <p *ngSwitchCase="red">Red</p>
    <p *ngSwitchCase="blue">Blue</p>
    <p *ngSwitchCase="green">Green</p>

As per the code above, it is getting very confusing to categorize ngSwtich to either of the Directive Categories! Can someone help me out in understanding the directive-type of ngSwitch ?

answered question

4 Answers


It is a structural directive

Structural directives updates the DOM layout by adding or removing elements.

posted this

As I understand it , 'structural directive' change the dom's struct. attribute directive change the dom's attribute,such as color,background and so on

ngSwitch change it's children's length , so its a structural directive,

posted this

[ngSwitch] is an attribute directive used in combination with *ngSwitchCase that is a structural directive.

This is clearly explained in Angular's documentation...

You'll get an error if you try to set *ngSwitch because NgSwitch is an attribute directive, not a structural directive. It changes the behavior of its companion directives. It doesn't touch the DOM directly.

Bind to *ngSwitchCase and *ngSwitchDefault. The NgSwitchCase and NgSwitchDefault directives are structural directives because they add or remove elements from the DOM.

posted this

Structural Directive:

What are structural directives?

Structural directives are responsible for HTML layout. They shape or reshape the DOM's structure, typically by adding, removing, or manipulating elements.

As with other directives, you apply a structural directive to a host element. The directive then does whatever it's supposed to do with that host element and its descendants.

Structural directives are easy to recognize. An asterisk (*) precedes the directive attribute name as in this example.


posted this

Have an answer?


Please login first before posting an answer.