Angular Directives Guide
Angular Directives are a powerful way to extend HTML with new attributes. They can be used to create reusable components and templates. This guide will introduce you to the basics of Angular Directives.
Overview
Angular Directives are used to:
- Extend the HTML vocabulary.
- Create reusable components.
- Implement custom behavior.
Types of Directives
- Structural Directives: Modify the DOM structure. For example,
ngFor
,ngIf
. - Attribute Directives: Modify the attributes of an element. For example,
ngModel
,ngStyle
. - Component Directives: Create reusable components. For example,
[ngComponentOutlet]
.
Example
Here's a simple example of a structural directive, ngFor
:
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>
This directive will create a list item for each item in the items
array.
More on ngFor
ngFor Directive
The ngFor
directive is used to iterate over an array and generate repeated HTML elements.
Syntax
<element *ngFor="let item of items" [property]="expression">
<!-- Content here -->
</element>
element
: The HTML element to repeat.item
: The variable representing each item in the array.items
: The array to iterate over.[property]
: Optional binding to a property of the item.
Example
<div *ngFor="let user of users" [ngStyle]="{'color': user.isActive ? 'green' : 'red'}">
{{ user.name }}
</div>
This example will color the names of active users green and inactive users red.
More on ngFor
ngModel Directive
The ngModel
directive is used to create two-way data binding between an input element and a data model.
Syntax
<input [(ngModel)]="dataModel">
dataModel
: The data model to bind to.
Example
<input [(ngModel)]="name">
This input will update the name
variable in the component whenever the user types in the input field.