What Are the Different Sorts of Directives?
This article outlines and explains the three different sorts of directives: components, structural directives, and attribute directives.
Join the DZone community and get the full member experience.Join For Free
There are principally three sorts of directives,
Components — Components are the most basic UI building block of an Angular app. An Angular app contains a tree of Angular components.
Angular components are a subset of directives, always associated with a template. Unlike other directives, only one component can be instantiated for a given element in a template.
A component must belong to a NgModule in order for it to be available to another component or application. To make it a member of a NgModule, list it in the
declarations field of the
Note that, in addition to these options for configuring a directive, you can control a component's runtime behavior by implementing life-cycle hooks.
Structural directives — A structural directive in a template controls whether that template is rendered at run time, based on its input expression. To help the compiler catch template type errors, you should specify as closely as possible the required type of a directive's input expression when it occurs inside the template.
A type guard function narrows the expected type of an input expression to a subset of types that might be passed to the directive within the template at run time. You can provide such a function to help the type-checker infer the proper type for the expression at compile time.
For example, the NgIf implementation uses type-narrowing to ensure that the template is only instantiated if the input expression to *ngIf is truthy. To provide the specific type requirement, the NgIf directive defines a static property ngTemplateGuard_ngIf: 'binding'. The binding value is a special case for a common kind of type-narrowing where the input expression is evaluated in order to satisfy the type requirement.
To provide a more specific type for an input expression to a directive within the template, add a ngTemplateGuard_xx property to the directive, where the suffix to the static property name, xx, is the @Input() field name. The value of the property can be either a general type-narrowing function based on its return type or the string "binding", as in the case of NgIf..
Attribute directives — These directives change the appearance or behavior of an element, component, or another directive.
Opinions expressed by DZone contributors are their own.