Decorators in angular

Nirmal Kumar
YavarTechWorks
Published in
3 min readNov 14, 2022

What is a decorator?

Decorators are a design pattern that is used to separate modification or decoration of a class without modifying the original source code.​​

Use of a decorator

The whole purpose of Angular decorators is to store metadata about a class, method, or property. When you configure a component.​

There are four main types of angular decorators:​​

  • Class decorators, such as @Component and @NgModule​​
  • Property decorators for properties inside classes, such as @Input and @Output
  • Method decorators for methods inside classes, such as @HostListener
  • Parameter decorators for parameters inside class constructors, such as @Inject

Class Decorators

Class decorators, also known as top-level decorators are used to inform Angular that a particular class is a component or module.​

Types of class decorators​​

@Component

@NgModule

@NgModule

Providers — A list of dependency injection (DI) providers and it defines the set of injectable objects that are available in the injector of this module. ​​

Declarations — A list of declarable classes, components, directives, that belong to this module. ​​

Imports — A list of modules and it used to import the supporting modules like FormsModule, RouterModule, CommonModule, or any other custom made feature module.​


Property Decorators

The use of Property decorators arises when component communication is required. Property decorators handle communication between parent and child components. There are various types of property decorator. Some of the most commonly used are:​​

@Input()​

@Output()

@Input()

Sending data to a child component

The @Input() decorator in a child component or directive signifies that the property can receive its value from its parent component.

@Output()

Sending data to a parent component from a child component

The @Output() decorator in a child component or directive lets data flow from the child to the parent.

Method decorator

Method decorators allow utilizing special decorator functions. For example @HostListener decorator observes events and allows us to tell Angular to call the decorator method when it is triggered.​

@HostListener

This tells Angular that when an event on your host happens, you want the decorated method to be called with the event.​

Parameter decorators

Parameter decorators are applied to the constructor parameter of the class and are used when we need to tell Angular to inject a particular provider in a constructor. @Inject() is a widely used parameter decorator. ​

@Inject()

@Injact is a widely used parameter decorator. We use this decorator to inject services in Angular classes.​

Thanks for reading! If you liked this article, hit that clap button below 👏.

--

--