I am so confused about Directives and Decorators in Angular. I thought anything prefixed with @ is a Decorator and now when i read about Directives it says, Component is a Directive. What's going on? Any clarity on the matter would be helpful.
Angular Directives & Decorators
Decorator:
A Decorator is a special kind of declaration that can be attached to a class declaration, method, accessor, property, or parameter. Decorators use the form @expression, where expression must evaluate to a function that will be called at runtime with information about the decorated declaration.
Here is an example decorator from the TypeScript docs called sealed:
function sealed(constructor: Function) {
Object.seal(constructor);
Object.seal(constructor.prototype);
}
You will note that it takes a constructor as an argument. It can be used on a class as follows:
@sealed class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return “Hello, “ + this.greeting;
}
}
Directives:
Angular Directive is basically a class with a @Directive decorator. A component is also a directive-with-a-template. A @Component decorator is actually a @Directive decorator extended with template-oriented features. Whenever Angular renders a directive, it changes the DOM according to the instructions given by the directive. The directive appears within an element tag similar to attributes.
The Angular Directive can be classified into two types: structural and attribute directives.
Structural directives alter layout by adding, removing, and replacing elements in DOM. Attribute directive alter the appearance or behavior of an existing element. When you include attribute directives in templates, they look like regular HTML attributes. The ngModel directive, which implements two-way data binding, is an example of an attribute directive. ngModel modifies the behavior of an existing element by setting its display property and responding to the changing events.
Notice how inside an Angular component we use the ngModel directive?
<label for="example-ngModel">[(ngModel)]:</label>
<input [(ngModel)]="currentItem.name" id="example-ngModel">