{ "id": "guide/built-in-directives", "title": "Built-in directives", "contents": "\n\n\n
\n mode_edit\n
\n\n\n
\n

Built-in directiveslink

\n

Directives are classes that add additional behavior to elements\nin your Angular applications.\nWith Angular's built-in directives, you can manage forms, lists, styles, and what users see.

\n
\n

See the for a working example containing the code snippets in this guide.

\n
\n

The different types of Angular directives are as follows:

\n
    \n
  1. Components—directives with a template.\nThis type of directive is the most common directive type.
  2. \n
  3. Attribute directives—directives that change the appearance or behavior of an element, component, or another directive.
  4. \n
  5. Structural directives—directives that change the DOM layout by adding and removing DOM elements.
  6. \n
\n

This guide covers built-in attribute directives and structural directives.

\n\n

Built-in attribute directiveslink

\n

Attribute directives listen to and modify the behavior of other HTML elements, attributes, properties, and components.

\n

Many NgModules such as the RouterModule and the FormsModule define their own attribute directives.\nThe most common attribute directives are as follows:

\n\n\n

Adding and removing classes with NgClasslink

\n

You can add or remove multiple CSS classes simultaneously with ngClass.

\n
\n

To add or remove a single class, use class binding rather than NgClass.

\n
\n

Using NgClass with an expressionlink

\n

On the element you'd like to style, add [ngClass] and set it equal to an expression.\nIn this case, isSpecial is a boolean set to true in app.component.ts.\nBecause isSpecial is true, ngClass applies the class of special to the <div>.

\n\n<!-- toggle the \"special\" class on/off with a property -->\n<div [ngClass]=\"isSpecial ? 'special' : ''\">This div is special</div>\n\n\n

Using NgClass with a methodlink

\n
    \n
  1. \n

    To use NgClass with a method, add the method to the component class.\nIn the following example, setCurrentClasses() sets the property currentClasses with an object that adds or removes three classes based on the true or false state of three other component properties.

    \n

    Each key of the object is a CSS class name.\nIf a key is true, ngClass adds the class.\nIf a key is false, ngClass removes the class.

    \n\n currentClasses: {};\n/* . . . */\n setCurrentClasses() {\n // CSS classes: added/removed per current state of component properties\n this.currentClasses = {\n saveable: this.canSave,\n modified: !this.isUnchanged,\n special: this.isSpecial\n };\n }\n\n\n
  2. \n
  3. \n

    In the template, add the ngClass property binding to currentClasses to set the element's classes:

    \n\n<div [ngClass]=\"currentClasses\">This div is initially saveable, unchanged, and special.</div>\n\n\n
  4. \n
\n

For this use case, Angular applies the classes on initialization and in case of changes.\nThe full example calls setCurrentClasses() initially with ngOnInit() and when the dependent properties change through a button click.\nThese steps are not necessary to implement ngClass.\nFor more information, see the app.component.ts and app.component.html.

\n\n

Setting inline styles with NgStylelink

\n

You can use NgStyle to set multiple inline styles simultaneously, based on the state of the component.

\n
    \n
  1. \n

    To use NgStyle, add a method to the component class.

    \n

    In the following example, setCurrentStyles() sets the property currentStyles with an object that defines three styles, based on the state of three other component properties.

    \n\n currentStyles: {};\n/* . . . */\n setCurrentStyles() {\n // CSS styles: set per current state of component properties\n this.currentStyles = {\n 'font-style': this.canSave ? 'italic' : 'normal',\n 'font-weight': !this.isUnchanged ? 'bold' : 'normal',\n 'font-size': this.isSpecial ? '24px' : '12px'\n };\n }\n\n\n
  2. \n
  3. \n

    To set the element's styles, add an ngStyle property binding to currentStyles.

    \n\n<div [ngStyle]=\"currentStyles\">\n This div is initially italic, normal weight, and extra large (24px).\n</div>\n\n\n
  4. \n
\n

For this use case, Angular applies the styles upon initialization and in case of changes.\nTo do this, the full example calls setCurrentStyles() initially with ngOnInit() and when the dependent properties change through a button click.\nHowever, these steps are not necessary to implement ngStyle on its own.\nSee the app.component.ts and app.component.html for this optional implementation.

\n\n

Displaying and updating properties with ngModellink

\n

You can use the NgModel directive to display a data property and update that property when the user makes changes.

\n
    \n
  1. \n

    Import FormsModule and add it to the NgModule's imports list.

    \n\nimport { FormsModule } from '@angular/forms'; // <--- JavaScript import from Angular\n/* . . . */\n@NgModule({\n/* . . . */\n\n imports: [\n BrowserModule,\n FormsModule // <--- import into the NgModule\n ],\n/* . . . */\n})\nexport class AppModule { }\n\n\n
  2. \n
  3. \n

    Add an [(ngModel)] binding on an HTML <form> element and set it equal to the property, here name.

    \n\n<label for=\"example-ngModel\">[(ngModel)]:</label>\n<input [(ngModel)]=\"currentItem.name\" id=\"example-ngModel\">\n\n\n

    This [(ngModel)] syntax can only set a data-bound property.

    \n
  4. \n
\n

To customize your configuration, you can write the expanded form, which separates the property and event binding.\nUse property binding to set the property and event binding to respond to changes.\nThe following example changes the <input> value to uppercase:

\n\n<input [ngModel]=\"currentItem.name\" (ngModelChange)=\"setUppercaseName($event)\" id=\"example-uppercase\">\n\n\n

Here are all variations in action, including the uppercase version:

\n
\n \"NgModel\n
\n

NgModel and value accessorslink

\n

The NgModel directive works for an element supported by a ControlValueAccessor.\nAngular provides value accessors for all of the basic HTML form elements.\nFor more information, see Forms.

\n

To apply [(ngModel)] to a non-form native element or a third-party custom component, you have to write a value accessor.\nFor more information, see the API documentation on DefaultValueAccessor.

\n
\n

When you write an Angular component, you don't need a value accessor or NgModel if you name the value and event properties according to Angular's two-way binding syntax.

\n
\n\n

Built-in structural directiveslink

\n

Structural directives are responsible for HTML layout.\nThey shape or reshape the DOM's structure, typically by adding, removing, and manipulating the host elements to which they are attached.

\n

This section introduces the most common built-in structural directives:

\n\n

For more information, see Structural Directives.

\n\n

Adding or removing an element with NgIflink

\n

You can add or remove an element by applying an NgIf directive to a host element.

\n

When NgIf is false, Angular removes an element and its descendants from the DOM.\nAngular then disposes of their components, which frees up memory and resources.

\n

To add or remove an element, bind *ngIf to a condition expression such as isActive in the following example.

\n\n<app-item-detail *ngIf=\"isActive\" [item]=\"item\"></app-item-detail>\n\n\n

When the isActive expression returns a truthy value, NgIf adds the ItemDetailComponent to the DOM.\nWhen the expression is falsy, NgIf removes the ItemDetailComponent from the DOM and disposes of the component and all of its sub-components.

\n

For more information on NgIf and NgIfElse, see the NgIf API documentation.

\n

Guarding against nulllink

\n

By default, NgIf prevents display of an element bound to a null value.

\n

To use NgIf to guard a <div>, add *ngIf=\"yourProperty\" to the <div>.\nIn the following example, the currentCustomer name appears because there is a currentCustomer.

\n\n<div *ngIf=\"currentCustomer\">Hello, {{currentCustomer.name}}</div>\n\n\n

However, if the property is null, Angular does not display the <div>.\nIn this example, Angular does not display the nullCustomer because it is null.

\n\n<div *ngIf=\"nullCustomer\">Hello, <span>{{nullCustomer}}</span></div>\n\n\n\n

Listing items with NgForlink

\n

You can use the NgFor directive to present a list of items.

\n
    \n
  1. \n

    Define a block of HTML that determines how Angular renders a single item.

    \n
  2. \n
  3. \n

    To list your items, assign the short hand let item of items to *ngFor.

    \n
  4. \n
\n\n<div *ngFor=\"let item of items\">{{item.name}}</div>\n\n\n

The string \"let item of items\" instructs Angular to do the following:

\n\n

For more information see the Structural directive shorthand section of Structural directives.

\n

Repeating a component viewlink

\n

To repeat a component element, apply *ngFor to the selector.\nIn the following example, the selector is <app-item-detail>.

\n\n<app-item-detail *ngFor=\"let item of items\" [item]=\"item\"></app-item-detail>\n\n\n

You can reference a template input variable, such as item, in the following locations:

\n\n

The following example references item first in an interpolation and then passes in a binding to the item property of the <app-item-detail> component.

\n\n <div *ngFor=\"let item of items\">{{item.name}}</div>\n<!-- . . . -->\n <app-item-detail *ngFor=\"let item of items\" [item]=\"item\"></app-item-detail>\n\n\n

For more information about template input variables, see Structural directive shorthand.

\n

Getting the index of *ngForlink

\n

You can get the index of *ngFor in a template input variable and use it in the template.

\n

In the *ngFor, add a semicolon and let i=index to the short hand.\nThe following example gets the index in a variable named i and displays it with the item name.

\n\n<div *ngFor=\"let item of items; let i=index\">{{i + 1}} - {{item.name}}</div>\n\n\n

The index property of the NgFor directive context returns the zero-based index of the item in each iteration.

\n

Angular translates this instruction into an <ng-template> around the host element,\nthen uses this template repeatedly to create a new set of elements and bindings for each item\nin the list.\nFor more information about shorthand, see the Structural Directives guide.

\n\n

Repeating elements when a condition is truelink

\n

To repeat a block of HTML when a particular condition is true, put the *ngIf on a container element that wraps an *ngFor element.\nOne or both elements can be an <ng-container> so you don't have to introduce extra levels of HTML.

\n

Because structural directives add and remove nodes from the DOM, apply only one structural directive per element.

\n

For more information about NgFor see the NgForOf API reference.

\n\n

Tracking items with *ngFor trackBylink

\n

By tracking changes to an item list, you can reduce the number of calls your application makes to the server.\nWith the *ngFor trackBy property, Angular can change and re-render only those items that have changed, rather than reloading the entire list of items.

\n
    \n
  1. \n

    Add a method to the component that returns the value NgFor should track.\nIn this example, the value to track is the item's id.\nIf the browser has already rendered id, Angular keeps track of it and doesn't re-query the server for the same id.

    \n\ntrackByItems(index: number, item: Item): number { return item.id; }\n\n\n
  2. \n
  3. \n

    In the short hand expression, set trackBy to the trackByItems() method.

    \n\n<div *ngFor=\"let item of items; trackBy: trackByItems\">\n ({{item.id}}) {{item.name}}\n</div>\n\n\n
  4. \n
\n

Change ids creates new items with new item.ids.\nIn the following illustration of the trackBy effect, Reset items creates new items with the same item.ids.

\n\n
\n \"Animation\n
\n
\n

Built-in directives use only public APIs.\nThey do not have special access to any private APIs that other directives can't access.

\n
\n\n

Hosting a directive without a DOM elementlink

\n

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.

\n

You can use <ng-container> when there's no single element to host the directive.

\n

Here's a conditional paragraph using <ng-container>.

\n\n<p>\n I turned the corner\n <ng-container *ngIf=\"hero\">\n and saw {{hero.name}}. I waved\n </ng-container>\n and continued on my way.\n</p>\n\n\n
\n \"ngcontainer\n
\n
    \n
  1. \n

    Import the ngModel directive from FormsModule.

    \n
  2. \n
  3. \n

    Add FormsModule to the imports section of the relevant Angular module.

    \n
  4. \n
  5. \n

    To conditionally exclude an <option>, wrap the <option> in an <ng-container>.

    \n\n<div>\n Pick your favorite hero\n (<label><input type=\"checkbox\" checked (change)=\"showSad = !showSad\">show sad</label>)\n</div>\n<select [(ngModel)]=\"hero\">\n <ng-container *ngFor=\"let h of heroes\">\n <ng-container *ngIf=\"showSad || h.emotion !== 'sad'\">\n <option [ngValue]=\"h\">{{h.name}} ({{h.emotion}})</option>\n </ng-container>\n </ng-container>\n</select>\n\n\n
    \n \"ngcontainer\n
    \n
  6. \n
\n\n

Switching cases with NgSwitchlink

\n

Like the JavaScript switch statement, NgSwitch displays one element from among several possible elements, based on a switch condition.\nAngular puts only the selected element into the DOM.

\n\n

NgSwitch is a set of three directives:

\n\n
    \n
  1. \n

    On an element, such as a <div>, add [ngSwitch] bound to an expression that returns the switch value, such as feature.\nThough the feature value in this example is a string, the switch value can be of any type.

    \n
  2. \n
  3. \n

    Bind to *ngSwitchCase and *ngSwitchDefault on the elements for the cases.

    \n\n<div [ngSwitch]=\"currentItem.feature\">\n <app-stout-item *ngSwitchCase=\"'stout'\" [item]=\"currentItem\"></app-stout-item>\n <app-device-item *ngSwitchCase=\"'slim'\" [item]=\"currentItem\"></app-device-item>\n <app-lost-item *ngSwitchCase=\"'vintage'\" [item]=\"currentItem\"></app-lost-item>\n <app-best-item *ngSwitchCase=\"'bright'\" [item]=\"currentItem\"></app-best-item>\n<!-- . . . -->\n <app-unknown-item *ngSwitchDefault [item]=\"currentItem\"></app-unknown-item>\n</div>\n\n\n
  4. \n
  5. \n

    In the parent component, define currentItem so you can use it in the [ngSwitch] expression.

    \n\ncurrentItem: Item;\n\n\n
  6. \n
  7. \n

    In each child component, add an item input property which is bound to the currentItem of the parent component.\nThe following two snippets show the parent component and one of the child components.\nThe other child components are identical to StoutItemComponent.

    \n\nexport class StoutItemComponent {\n @Input() item: Item;\n}\n\n\n
    \n \"Animation\n
    \n
  8. \n
\n

Switch directives also work with native HTML elements and web components.\nFor example, you could replace the <app-best-item> switch case with a <div> as follows.

\n\n<div *ngSwitchCase=\"'bright'\"> Are you as bright as {{currentItem.name}}?</div>\n\n\n

What's nextlink

\n

For information on how to build your own custom directives, see Attribute Directives and Structural Directives.

\n\n \n
\n\n\n" }