Core Directives in Angular 2.0

- Developer and Blogger
Published: Sun Jun 28 2015

In Angular 2.0 – core directives are not automatically available in your templates. Instead you have to opt in to the directives you plan to use in your components. In cases where you need several it may seem a bit tedious to list out every single one. In the following post I will show how to include all core directives using the predefined 'CORE_DIRECTIVES' constant.

The code listing below shows how to define a component with access to all core directives:

import {CORE_DIRECTIVES,Component,View} from 'angular2/angular2'; @Component({ selector: 'core-directives', properties: ['numbers: numbers'] }) @View({ templateUrl: './components/core-directives/core-directives.html', directives: [CORE_DIRECTIVES] }) export class CoreDirectives { numbers: Array<Number>; constructor(){ this.numbers = [1,2,3,4,5,6,7,8,9,10]; } }

The key to including all directives is the imported 'CORE_DIRECTIVES' constant.

As you can tell from the template I am now able to use built in directives like ng-for and ng-if without listing them out individually in the component.

<div *ng-for="#number of numbers"> <p *ng-if="number % 2 === 0">{{number}}</p> </div>

I have added this sample code to my Github repo.

You can also see a live demo here.

I invite you to follow me on twitter