Angular Directives are a powerful feature of Angular that allow you to extend HTML with new attributes. They can be used to create reusable components, manipulate the DOM, and add behavior to your application.

Types of Directives

  1. Attribute Directives: These directives are applied to an attribute of an element. For example, [ngModel] is an attribute directive that binds the input element to a model in your component.
  2. Structural Directives: These directives change the structure of the DOM. For example, *ngFor is a structural directive that repeats a chunk of HTML for each item in a list.
  3. Event Directives: These directives listen to events on the DOM. For example, (click) is an event directive that executes a function when the element is clicked.

Example of Attribute Directive

Here's an example of how to use an attribute directive:

<input [ngModel]="myModel" placeholder="Type something...">

In this example, the [ngModel] directive binds the input element to the myModel property in your component.

Example of Structural Directive

Here's an example of how to use a structural directive:

<ul>
  <li *ngFor="let item of items">{{ item }}</li>
</ul>

In this example, the *ngFor directive repeats the <li> element for each item in the items array.

Example of Event Directive

Here's an example of how to use an event directive:

<button (click)="myFunction()">Click me!</button>

In this example, the (click) directive executes the myFunction() method when the button is clicked.

Further Reading

For more information on Angular Directives, you can visit the official Angular documentation: Angular Directives.


Angular Logo