Angular decorators

The decorators in Typescript are like annotations in Java, They are just functions that can be used to add meta-data, properties or functions to the thing they are attached to. They give Angular the ability to store metadata for classes and streamline our workflow simultaneously.

Different Types of Angular Decorators

Before we look at creating a custom decorator and why/how Angular uses them, let’s look at the different types of decorators that Angular offers. There are four main types:

  • Class decorators – e.g. @Component and @NgModule
  • Property decorators for properties inside classes – e.g. @Input and @Output
  • Method decorators for methods inside classes – e.g. @HostListener
  • Parameter decorators for parameters inside class constructors – e.g. @Inject

Examples:

Class decorator Example:

@NgModule({
  declarations: [
    AppComponent, NavbarComponent, routingComponents, HomeComponent, 
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFirestoreModule,
    FormsModule,
    RecaptchaModule.forRoot(), //For Recaptcha
  ],
  providers: [MetaService, Title],
  bootstrap: [AppComponent]
})
export class AppModule { }

And

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
  })
export class AppComponent {
  title = 'ProgrammerToday';
}

List of decorators available in Angular:

  • @NgModule
  • @Component
  • @Injectable
  • @Directive
  • @Pipe
  • @Input
  • @Output
  • @HostBinding
  • @HostListener
  • @ContentChild
  • @ContentChildren
  • @ViewChild
  • @ViewChildren

How to Create custom Decorator ?

Let’s quickly make a decorator that we can use on a class to demonstrate this a little further. 

Example : This decorator is just going to simply log a message to the console:

function LoggerConsole() {
  console.log('This is a logger's log');
}

Apply it over a class, for example

@Console
class SampleClass {
  constructor() {
    console.log('Hi!');
  }
}

OUTPUT

This is a logger’s log

Summary

In this article we learnt what is a decorator, how many types of decorators, a couple of examples and how to create your own custom decorator.

Hope you like it !