Built-in directives
Directives are classes that add additional behavior to elements in your Angular applications.
Use Angular's built-in directives to manage forms, lists, styles, and what users see.
The different types of Angular directives are as follows:
| Directive Types | Details |
|---|---|
| Components | Used with a template. This type of directive is the most common directive type. |
| Attribute directives | Change the appearance or behavior of an element, component, or another directive. |
| Structural directives | Change the DOM layout by adding and removing DOM elements. |
This guide covers built-in attribute directives.
Built-in attribute directives
Attribute directives listen to and modify the behavior of other HTML elements, attributes, properties, and components.
The most common attribute directives are as follows:
| Common directives | Details |
|---|---|
NgClass |
Adds and removes a set of CSS classes. |
NgStyle |
Adds and removes a set of HTML styles. |
NgModel |
Adds two-way data binding to an HTML form element. |
HELPFUL: Built-in directives use only public APIs. They do not have special access to any private APIs that other directives can't access.
Adding and removing classes with NgClass
Add or remove multiple CSS classes simultaneously with ngClass.
HELPFUL: To add or remove a single class, use class binding rather than NgClass.
Import NgClass in the component
To use NgClass, add it to the component's imports list.
app.component.ts (NgClass import)
import {NgClass} from '@angular/common';/* . . . */@Component({ /* . . . */ NgClass, // <-- import into the component /* . . . */ ],})export class AppComponent implements OnInit { /* . . . */}
Using NgClass with an expression
On the element you'd like to style, add [ngClass] and set it equal to an expression.
In this case, isSpecial is a boolean set to true in app.component.ts.
Because isSpecial is true, ngClass applies the class of special to the <div>.
app.component.html
<!-- toggle the "special" class on/off with a property --><div [ngClass]="isSpecial ? 'special' : ''">This div is special</div>
Using NgClass with a method
To use
NgClasswith a method, add the method to the component class. In the following example,setCurrentClasses()sets the propertycurrentClasseswith an object that adds or removes three classes based on thetrueorfalsestate of three other component properties.Each key of the object is a CSS class name. If a key is
true,ngClassadds the class. If a key isfalse,ngClassremoves the class.app.component.ts
currentClasses: Record<string, boolean> = {}; /* . . . */ setCurrentClasses() { // CSS classes: added/removed per current state of component properties this.currentClasses = { saveable: this.canSave, modified: !this.isUnchanged, special: this.isSpecial, }; }In the template, add the
ngClassproperty binding tocurrentClassesto set the element's classes:
app.component.html
<div [ngClass]="currentClasses">This div is initially saveable, unchanged, and special.</div>
For this use case, Angular applies the classes on initialization and in case of changes caused by reassigning the currentClasses object.
The full example calls setCurrentClasses() initially with ngOnInit() when the user clicks on the Refresh currentClasses button.
These steps are not necessary to implement ngClass.
Setting inline styles with NgStyle
HELPFUL: To add or remove a single style, use style bindings rather than NgStyle.
Import NgStyle in the component
To use NgStyle, add it to the component's imports list.
app.component.ts (NgStyle import)
import {NgStyle} from '@angular/common';/* . . . */@Component({ /* . . . */ NgStyle, // <-- import into the component /* . . . */ ],})export class AppComponent implements OnInit { /* . . . */}
Use NgStyle to set multiple inline styles simultaneously, based on the state of the component.
To use
NgStyle, add a method to the component class.In the following example,
setCurrentStyles()sets the propertycurrentStyleswith an object that defines three styles, based on the state of three other component properties.app.component.ts
currentStyles: Record<string, string> = {}; /* . . . */ setCurrentStyles() { // CSS styles: set per current state of component properties this.currentStyles = { 'font-style': this.canSave ? 'italic' : 'normal', 'font-weight': !this.isUnchanged ? 'bold' : 'normal', 'font-size': this.isSpecial ? '24px' : '12px', }; }To set the element's styles, add an
ngStyleproperty binding tocurrentStyles.
app.component.html
<div [ngStyle]="currentStyles"> This div is initially italic, normal weight, and extra large (24px).</div>
For this use case, Angular applies the styles upon initialization and in case of changes.
To do this, the full example calls setCurrentStyles() initially with ngOnInit() and when the dependent properties change through a button click.
However, these steps are not necessary to implement ngStyle on its own.
Hosting a directive without a DOM element
The Angular <ng-container> is a grouping element that doesn't interfere with styles or layout because Angular doesn't put it in the DOM.
Use <ng-container> when there's no single element to host the directive.
Here's a conditional paragraph using <ng-container>.
app.component.html (ngif-ngcontainer)
<p> I turned the corner <ng-container *ngIf="hero"> and saw {{hero.name}}. I waved </ng-container> and continued on my way.</p>
Import the
ngModeldirective fromFormsModule.Add
FormsModuleto the imports section of the relevant Angular module.To conditionally exclude an
<option>, wrap the<option>in an<ng-container>.app.component.html (select-ngcontainer)
<div> Pick your favorite hero (<label for="showSad"><input id="showSad" type="checkbox" checked (change)="showSad = !showSad">show sad</label>)</div><select [(ngModel)]="hero"> <ng-container *ngFor="let h of heroes"> <ng-container *ngIf="showSad || h.emotion !== 'sad'"> <option [ngValue]="h">{{h.name}} ({{h.emotion}})</option> </ng-container> </ng-container></select>