×
☰ See All Chapters

Angular Directives

A directive is a marker inserted into a template element that alters the element's behavior. The angular core directives and their classes are provided automatically. That is, they don't need to be imported and they don't need to be added to the declarations array in the @NgModule annotation. Every directive has an associated class whose names take the form NgXyz, such as NgIf and NgStyle. When these directives are used inside template element they should be written with a lowercase 'n', as in ngIf and ngStyle.

There are two kinds of directives in Angular:

  • Structural directives 

  • Attribute directives 

Structural directives

Structural directives can change the DOM layout by adding and removing DOM elements. When these directives are used in templates, all structural Directives are preceded by asterisk symbol. Below are the commonly used structural directives.

  • ngIf : Adds or removes an element depending on a condition 

  • ngFor : Adds multiple elements to the document 

  • ngSwitch : Adds one of many elements to the document 

  • ngSwitchCase : Used with NgSwitch to identify an option 

  • ngSwitchDefault : Used with NgSwitch to identify the default option 

Attribute directives

An Attribute or style directive can change the appearance or behavior of an element. Below are the commonly used Attribute directives.

  • ngModel : The ngModel directive is used the achieve the two-way data binding. We have covered ngModel directive in Data Binding. 

  • ngClass : The ngClass is used to add or remove the CSS classes from an HTML element. Using the ngClass one can create dynamic styles in HTML pages 

  • ngStyle : ngStyle is used to change the multiple style properties of our HTML elements. We can also bind these properties to values that can be updated by the user or our components. 

 


All Chapters
Author