W3cubDocs

/Angular

Directive

decorator

Decorator that marks a class as an Angular directive. You can define your own directives to attach custom behavior to elements in the DOM.

See more...

Option Description
selector?

The CSS selector that identifies this directive in a template and triggers instantiation of the directive.

inputs?

Enumerates the set of data-bound input properties for a directive

outputs?

Enumerates the set of event-bound output properties.

providers?

Configures the injector of this directive or component with a token that maps to a provider of a dependency.

exportAs?

Defines the name that can be used in the template to assign this directive to a variable.

queries?

Configures the queries that will be injected into the directive.

host?

Maps class properties to host element bindings for properties, attributes, and events, using a set of key-value pairs.

jit?

When present, this directive/component is ignored by the AOT compiler. It remains in distributed code, and the JIT compiler attempts to compile it at run time, in the browser. To ensure the correct behavior, the app must import @angular/compiler.

standalone? developer preview

Angular directives marked as standalone do not need to be declared in an NgModule. Such directives don't depend on any "intermediate context" of an NgModule (ex. configured providers).

Subclasses

Description

The options provide configuration metadata that determines how the directive should be processed, instantiated and used at runtime.

Directive classes, like component classes, can implement life-cycle hooks to influence their configuration and behavior.

Further information is available in the Usage Notes...

Options

The CSS selector that identifies this directive in a template and triggers instantiation of the directive.

selector?: string

Declare as one of the following:

  • element-name: Select by element name.
  • .class: Select by class name.
  • [attribute]: Select by attribute name.
  • [attribute=value]: Select by attribute name and value.
  • :not(sub_selector): Select only if the element does not match the sub_selector.
  • selector1, selector2: Select if either selector1 or selector2 matches.

Angular only allows directives to apply on CSS selectors that do not cross element boundaries.

For the following template HTML, a directive with an input[type=text] selector, would be instantiated only on the <input type="text"> element.

<form>
  <input type="text">
  <input type="radio">
<form>

Enumerates the set of data-bound input properties for a directive

inputs?: string[]

Angular automatically updates input properties during change detection. The inputs property defines a set of directiveProperty to bindingProperty configuration:

  • directiveProperty specifies the component property where the value is written.
  • bindingProperty specifies the DOM property where the value is read from.

When bindingProperty is not provided, it is assumed to be equal to directiveProperty.

The following example creates a component with two data-bound properties.

@Component({
  selector: 'bank-account',
  inputs: ['bankName', 'id: account-id'],
  template: `
    Bank Name: {{bankName}}
    Account Id: {{id}}
  `
})
class BankAccount {
  bankName: string;
  id: string;
}

Enumerates the set of event-bound output properties.

outputs?: string[]

When an output property emits an event, an event handler attached to that event in the template is invoked.

The outputs property defines a set of directiveProperty to bindingProperty configuration:

  • directiveProperty specifies the component property that emits events.
  • bindingProperty specifies the DOM property the event handler is attached to.
@Component({
  selector: 'child-dir',
  outputs: [ 'bankNameChange' ]
  template: `<input (input)="bankNameChange.emit($event.target.value)" />`
})
class ChildDir {
 bankNameChange: EventEmitter<string> = new EventEmitter<string>();
}

@Component({
  selector: 'main',
  template: `
    {{ bankName }} <child-dir (bankNameChange)="onBankNameChange($event)"></child-dir>
  `
})
class MainComponent {
 bankName: string;

  onBankNameChange(bankName: string) {
    this.bankName = bankName;
  }
}

Configures the injector of this directive or component with a token that maps to a provider of a dependency.

providers?: Provider[]

Defines the name that can be used in the template to assign this directive to a variable.

exportAs?: string

@Directive({
  selector: 'child-dir',
  exportAs: 'child'
})
class ChildDir {
}

@Component({
  selector: 'main',
  template: `<child-dir #c="child"></child-dir>`
})
class MainComponent {
}

Configures the queries that will be injected into the directive.

queries?: { [key: string]: any; }

Content queries are set before the ngAfterContentInit callback is called. View queries are set before the ngAfterViewInit callback is called.

The following example shows how queries are defined and when their results are available in lifecycle hooks:

@Component({
  selector: 'someDir',
  queries: {
    contentChildren: new ContentChildren(ChildDirective),
    viewChildren: new ViewChildren(ChildDirective)
  },
  template: '<child-directive></child-directive>'
})
class SomeDir {
  contentChildren: QueryList<ChildDirective>,
  viewChildren: QueryList<ChildDirective>

  ngAfterContentInit() {
    // contentChildren is set
  }

  ngAfterViewInit() {
    // viewChildren is set
  }
}

Maps class properties to host element bindings for properties, attributes, and events, using a set of key-value pairs.

host?: { [key: string]: string; }

Angular automatically checks host property bindings during change detection. If a binding changes, Angular updates the directive's host element.

When the key is a property of the host element, the property value is the propagated to the specified DOM property.

When the key is a static attribute in the DOM, the attribute value is propagated to the specified property in the host element.

For event handling:

  • The key is the DOM event that the directive listens to. To listen to global events, add the target to the event name. The target can be window, document or body.
  • The value is the statement to execute when the event occurs. If the statement evaluates to false, then preventDefault is applied on the DOM event. A handler method can refer to the $event local variable.

When present, this directive/component is ignored by the AOT compiler. It remains in distributed code, and the JIT compiler attempts to compile it at run time, in the browser. To ensure the correct behavior, the app must import @angular/compiler.

jit?: true

Angular directives marked as standalone do not need to be declared in an NgModule. Such directives don't depend on any "intermediate context" of an NgModule (ex. configured providers).

standalone?: boolean

More information about standalone components, directives and pipes can be found in this guide.

Usage notes

To define a directive, mark the class with the decorator and provide metadata.

import {Directive} from '@angular/core';

@Directive({
  selector: 'my-directive',
})
export class MyDirective {
...
}

Declaring directives

In order to make a directive available to other components in your application, you should do one of the following:

  • either mark the directive as standalone,
  • or declare it in an NgModule by adding it to the declarations and exports fields.

Marking a directive as standalone

You can add the standalone: true flag to the Directive decorator metadata to declare it as standalone:

@Directive({
  standalone: true,
  selector: 'my-directive',
})
class MyDirective {}

When marking a directive as standalone, please make sure that the directive is not already declared in an NgModule.

Declaring a directive in an NgModule

Another approach is to declare a directive in an NgModule:

@Directive({
  selector: 'my-directive',
})
class MyDirective {}

@NgModule({
  declarations: [MyDirective, SomeComponent],
  exports: [MyDirective], // making it available outside of this module
})
class SomeNgModule {}

When declaring a directive in an NgModule, please make sure that:

  • the directive is declared in exactly one NgModule.
  • the directive is not standalone.
  • you do not re-declare a directive imported from another module.
  • the directive is included into the exports field as well if you want this directive to be accessible for components outside of the NgModule.

© 2010–2022 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://angular.io/api/core/Directive