Structural Directives:
- ngIf: It is used to conditionally renders or removes an element based on a given expression.
Example:
<div *ngIf="isLoggedIn">Welcome, {{ username }}!</div>
The above div tag is rendered if and only if the value of the variable isLoggedIn turns to be True.
Likewise,For React developers reference,In React we use useState hook to do the same conditional rendering.
2.ngFor:
Renders a template for each item in a collection. In Angular, the ngFor structural directive is used to render a template for each item in a collection by iterating through collections (arrays or objects).It is very similar to for loop in programming language.
Example :
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>
In the above example, the items is the array or object which contains the list of values to be rendered say bunch of students.The variable item is used to iterate the loop , it is also called the loop variable.
This directive is used when we have a dynamic data instead of typing multiple statements.
3.ngSwitch:
In Angular ,ngSwitch is used to switch between multiple templates based on the value of the condition expression.
Here's a breakdown of how it works:
<div [ngSwitch]="condition">
<p *ngSwitchCase="'A'">Option A</p>
<p *ngSwitchCase="'B'">Option B</p>
<p *ngSwitchDefault>Default Option</p>
</div>
Binds the component's condition value to the ngSwitch directive using the syntax [ngSwitch]="condition". Which template within the ngSwitch block should be displayed depends on the value of condition.
ngSwitchCase="'A'":
When the condition's value matches the case value provided (in this case, "A"), the *ngSwitchCase directive defines a template to be displayed. The p> element containing the text "Option A" will be rendered if condition equals "A."
- ngSwitchCase="'B'":
This *ngSwitchCase directive defines a template to be displayed when the value of the condition matches the case value ('B'), similar to the previous case. The p> element containing the text "Option B" will be rendered if condition equals "B".
When none of the ngSwitchCase values match the value of condition, the *ngSwitchDefault directive is used to specify a default template that will be displayed. The element with the text "Default Option" will be shown if condition matches no situations.
The "Option A", "Option B", or "Default Option" will be displayed in this example depending on the value of the condition.
This gives flexibility in presenting content based on criteria and enables dynamic rendering of various templates based on the value of a variable or expression.
There are more angular directives like
1.Attributes directives
2.Custom directives
We will see about these topics in the next post.
Happy coding...😉
Top comments (0)