An Interest In:
Web News this Week
- April 3, 2024
- April 2, 2024
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
Angular Directives in 5 minutes
So what are directives?
These are attributes added to our DOM elements, that make them dynamic. They supercharge our DOM by adding extra functionality.
In angular there are two types of directives. Structural and Attribute directives.
Structural directives, change the DOM layout, by adding or removing content. Some examples include *ngIf and *ngFor.
On the other hand attribute directives, change the behavior of an element. Some examples include *ngClass and *ngStyle.
In this post, we will be looking at the most commonly used directives.
*ngIf
This directive conditionally shows content based on an expression's value.
Syntax:
*ngIf="expression"
Example:
If our expression results in a truthy value, our HTML tag will be rendered. In this case our expression is false, so the p tag will not be rendered
*ngFor
This directive repeats a given DOM element for each element found in an array.
Syntax:
*ngFor="let item of items"
Here our array is the fruits array, and we reference each item in the array as fruit. Then we display it in our component using interpolation.
*ngStyle
This directive allows us to add styles dynamically to our tags.
Syntax:
In its simplest form, it is just property binding
We bind the background color of this div to be red
Plain syntax:
[ngStyle]="{style: expression}"
In this case, we bind it directly to a property in our logic. So our div will be red.
*ngClass
This directive allows us to set classes dynamically to our elements.
Syntax:
[ngClass]="{cssClass: expression}"
Directives are powerful, when it comes to handling logic, there is a lot more to directives. We can even create our own custom directives.
Original Link: https://dev.to/eldrige/angular-directives-in-5-minutes-3ja2
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To