ANGULAR
Complete Angular Tutorial For Beginners Introduction to Angular | What is Angular? Architecture Overview & Concepts of Angular How to Install Angular How to Create a new project in Angular Bootstrapping in Angular: How It Works Internally Angular Components Overview & Examples Data Binding in Angular Interpolation in Angular Property Binding in Angular Event Binding in Angular ngModel & Two way Data binding in Angular NgModelChange & Change Event in Angular Child/Nested Components in Angular angular directives angular ngFor directive ngSwitch, ngSwitchcase, ngSwitchDefa ult Angular Example How to use ngIf, else, then in Angular By example NgClass Example Conditionally apply class Angular ngStyle Directive Angular Trackby to improve ngFor Performance How to Create & Use Custom Directive In Angular Working with Angular Pipes How to Create Custom Pipe in Angular Formatting Dates with Angular Date Pipe Using Angular Async Pipe with ngIf & ngFor angular keyValue pipe Using Angular Pipes in Components or Services Angular Component Communication & Sharing Data Angular Pass data to child component Angular Pass data from Child to parent component Component Life Cycle Hooks in Angular Angular ngOnInit And ngOnDestroy Life Cycle hook Angular ngOnChanges life Cycle Hook Angular ngDoCheck Life Cycle Hook Angular Forms Tutorial: Fundamentals & Concep t s Angular Template-driven forms example How to set value in template-driven forms in Angular Angular Reactive Forms Example Using Angular FormBuilder to build Forms SetValue & PatchValue in Angular StatusChanges in Angular Forms ValueChanges in Angular Forms FormControl in Angular FormGroup in Angular Angular FormArray Example Nested FormArray Example Add Form Fields Dynamically SetValue & PatchValue in FormArray Angular Select Options Example in Angular Introduction to Angular Services Introduction to Angular Dependency Injection Angular Injector, @Injectable & @Inject Angular Providers: useClass, useValue, useFactory & useExisting Injection Token in Angular How Dependency Injection & Resolution Works in Angular Angular Singleton Service ProvidedIn root, any & platform in Angular @Self, @SkipSelf & @Optional Decorators Angular '@Host Decorator in Angular ViewProviders in Angular Angular Reactive Forms Validation Custom Validator in Angular Reactive Form Custom Validator with Parameters in Angular Inject Service Into Validator in Angular template_driven_form_validation_in_angular Custom Validator in Template Driven Forms in Angular Angular Async Validator Example Cross Field or Multi Field Validation Angular How to add Validators Dynamically using SetValidators in Angular Angular HttpClient Tutorial & Example Angular HTTP GET Example using httpclient Angular HTTP POST Example URL Parameters, Query Parameters, httpparams in Angular HttpClient Angular HTTPHeaders Example Understanding HTTP Interceptors in Angular Angular Routing Tutorial with Example Location Strategy in Angular Angular Route Params Angular : Child Routes / Nested Route Query Parameters in Angular Angular Pass Data to Route: Dynamic/Static RouterLink, Navigate & NavigateByUrl to Navigate Routes RouterLinkActive in Angular Angular Router Events ActivatedRoute in Angular Angular Guards Tutorial Angular CanActivate Guard Example Angular CanActivateChild Example Angular CanDeactivate Guard Angular Resolve Guard Introduction to Angular Modules or ngModule Angular Routing between modules Angular Folder Structure Best Practices Guide to Lazy loading in Angular Angular Preloading Strategy Angular CanLoad Guard Example Ng-Content & Content Projection in Angular Angular @input, @output & EventEmitter Template Reference Variable in Angular ng-container in Angular How to use ng-template & TemplateRef in Angular How to Use ngTemplateOutlet in Angular '@Hostbinding and @Hostlistener_in_Angular Understanding ViewChild, ViewChildren &erylist in Angular ElementRef in Angular Renderer2 Example: Manipulating DOM in Angular ContentChild and ContentChildren in Angular AfterViewInit, AfterViewChecked, AfterContentInit & AfterContentChecked in Angular Angular Decorators Observable in Angular using RxJs Create observable from a string, array & object in angular Create Observable from Event using FromEvent in Angular Using Angular observable pipe with example Angular Map Operator: Usage and Examples Filter Operator in Angular Observable Tap operator in Angular observable Using SwitchMap in Angular Using MergeMap in Angular Using concatMap in Angular Using ExhaustMap in Angular Take, TakeUntil, TakeWhile & TakeLast in Angular Observable First, Last & Single Operator in Angular Observable Skip, SkipUntil, SkipWhile & SkipLast Operators in Angular The Scan & Reduce operators in Angular DebounceTime & Debounce in Angular Delay & DelayWhen in Angular Using ThrowError in Angular Observable Using Catcherror Operator in Angular Observable ReTryWhen inReTry, ReTryWhen in Angular Observable Unsubscribing from an Observable in Angular Subjects in Angular ReplaySubject, BehaviorSubject & AsyncSubject in Angular Angular Observable Subject Example Sharing Data Between Components Angular Global CSS styles View Encapsulation in Angular Style binding in Angular Class Binding in Angular Angular Component Styles How to Install & Use Angular FontAwesome How to Add Bootstrap to Angular Angular Location Service: go/back/forward Angular How to use APP_INITIALIZER Angular Runtime Configuration Angular Environment Variables Error Handling in Angular Applications Angular HTTP Error Handling Angular CLI tutorial ng new in Angular CLI How to update Angular to latest version Migrate to Standalone Components in Angular Create Multiple Angular Apps in One Project Set Page Title Using Title Service Angular Example Dynamic Page Title based on Route in Angular Meta service in Angular. Add/Update Meta Tags Example Dynamic Meta Tags in Angular Angular Canonical URL Lazy Load Images in Angular Server Side Rendering Using Angular Universal The requested URL was not found on this server error in Angular Angular Examples & Sample Projects Best Resources to Learn Angular Best Angular Books in 2020

Angular Decorators

We use Angular Decorators to Provide metadata to a class declaration, method, accessor, property, or parameter in Angular. We use it at many places in our Angular App. We use it to decorate components, directives, Angular Modules, etc. In this article, let us learn what is Angular Decorator, Why it is needed, and How to create a custom Angular Decorator. We also learn list of built-in Decorators that Angular Supports.

Angular Decorators

An Angular Decorator is a function, using which we attach metadata to a class declaration, method, accessor, property, or parameter.

We apply the decorator using the form @expression, where expression is the name of the decorator.

For Example, @Component is an Angular Decorator, which we attach to an Angular Component. When Angular sees the @Component decorator applied to a class, it treats the class as a component class. In the following example, it is the @Component decorator that makes AppComponent an Angular Component. Without the decorator, AppComponent is just like any other class.

                              

@Component({
})
export class AppComponent {
  title = 'app';
} 
 
                            
                        

The decorator is a Typescript feature and it is still not part of the Javascript. It is still in the Proposal stage.

To enable Angular Decorators, we need to add the experimentalDecorators to the tsconfig.json file. The ng new command automatically adds this for us.

                              
 
{
  "compilerOptions": {
    "target": "ES5",
    "experimentalDecorators": true
  }
}
 
                            
                        

Why we need Angular Decorators

Angular uses the Decorators to Provide metadata to the class, method, or property.

For example, the AppComponent must know where to find its template. We do that by using the templateUrl parameter of the @Component directive. The @Component decorator also accepts the values for styleUrls, encapsulation, changeDetection, etc, which Angular uses to configure the component.

                              
@Component({
  templateUrl: './app.component.html',
 
})
export class AppComponent {
 
                            
                        

To understand how a decorator works let us build a class decorator named simpleDecorator.

Creating a new Decorator in Angular

We use the decorator in the form @expression, where expression is the name of the decorator and it must be evaluate to a function.

In the following example, we create a function simpleDecorator. We will use it to decorate the AppComponent class. The function does not take any arguments.

                              

import { Component, VERSION } from '@angular/core';
 
@simpleDecorator      
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular ' + VERSION.major;
 
  constructor() {
    console.log('Hello from Class constructor');
  }
 
  ngOnInit() {
    console.log((this as any).value1);
    console.log((this as any).value2);
  }
}
 
function simpleDecorator(target: any) {
  console.log('Hello from Decorator');
 
  Object.defineProperty(target.prototype, 'value1', {
    value: 100,
    writable: false
  });
 
  Object.defineProperty(target.prototype, 'value2', {
    value: 200,
    writable: false
  });
}
 
 
 
**** Console ***
 
Hello from Decorator
Hello from Class constructor
100
200
 
                            
                        

You can refer StackBlitz for the complete code.

As we said earlier, the decorator is a regular JavaScript function. Since we are using it using it on class, It gets the instance of the AppComponent as a argument (target)

                              

function simpleDecorator(target: any) {
  console.log('Hello from Decorator');
 
//target is instance of AppComponent
 
                            
                        

Inside the function, we add two custom properties value1 & value2 to our AppComponent. Note that we use the defineProperty property to add a new property to the component class. Also, we add it to the prototype property of the class

                              
Object.defineProperty(target.prototype, 'value1', {
    value: 100,
    writable: false
  });
 
  Object.defineProperty(target.prototype, 'value2', {
    value: 200,
    writable: false
  });
 
                            
                        

Now, we can use it to Decorate our AppComponent

                              

@simpleDecorator
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
 
                            
                        

Inside the component, we can access the new properties using the keyword “this”.

                              

  ngOnInit() {
    console.log((this as any).value1);
    console.log((this as any).value2);
  }
                            
                        

Decorator with Arguments

To Create a Decorator with arguments, we need to create a factory function, which returns the Decorator function. You can refer to the StackBlitz

                              

import { Component, VERSION } from '@angular/core';
 
@simpleDecorator({
  value1: '100',
  value2: '200'
})
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular ' + VERSION.major;
 
  constructor() {
    console.log('Hello from Class constructor');
  }
 
  ngOnInit() {
    console.log((this as any).value1);
    console.log((this as any).value2);
  }
}
 
function simpleDecorator(args) {
  console.log(args);
 
  return function(target: any) {
    console.log('Hello from Decorator');
    console.log(typeof target);
    console.log(target);
 
    Object.defineProperty(target.prototype, 'value1', {
      value: args.value1,
      writable: false
    });
 
    Object.defineProperty(target.prototype, 'value2', {
      value: args.value2,
      writable: false
    });
  };
}
 
 
                            
                        

The simpleDecorator takes the args as argument and returns the decorator function. The rest of the code is as same as above, except we use the args to populate the properties.

                              

function simpleDecorator(args) {
  console.log(args);
 
  return function(target: any) {
 
                            
                        

We apply the simpleDecorator on the component as below

                              

@simpleDecorator({
  value1: '100',
  value2: '200'
})
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
 
                            
                        

List of All Angular Decorators

Angular provides several built in Decorators. We can classify them under four different categories

  1. Class decorators.
  2. Property decorators
  3. Method decorators
  4. Parameter decorators

The following is a complete list of Decorators in Angular.

Class Decorators
  1. @NgModule
  2. @Component
  3. @Injectable
  4. @Directive
  5. @Pipe
Property decorators
  1. @Input
  2. @Output
  3. @HostBinding
  4. @ContentChild
  5. @ContentChildren
  6. @ViewChild
  7. @ViewChildren
Method decorators
  1. @HostListener
Parameter decorators
  1. @Inject
  2. @Self
  3. @SkipSelf
  4. @Optional
  5. @Host

Class decorators

We apply class decorators to classes. @NgModule, @Component, @Injectable, @Directive & @Pipe are Class Decorators in Angular

@NgModule

@NgModule Decorator defines the class as Angular Module and adds the required metadata to it.

                              
 
@NgModule({
  providers?: Provider[],
  declarations?: Array<Type<any> | any[]>,
  imports?: Array<Type<any> | ModuleWithProviders<{}> | any[]>,
  exports?: Array<Type<any> | any[]>,
  bootstrap?: Array<Type<any> | any[]>,
  schemas?: Array<SchemaMetadata | any[]>,
  id?: string,
  jit?: true
})
                            
                        

@Component

The Angular recognizes the class as Angular Component only if we decorate it with the @Component Decorator.

                              

@Component({
  changeDetection?: ChangeDetectionStrategy,
  viewProviders?: Provider[],
  moduleId?: string,
 
  templateUrl?: string,
  template?: string,
  styleUrls?: string[],
  styles?: string[],
  animations?: any[],
  encapsulation?: ViewEncapsulation,
  interpolation?: [string, string],
  preserveWhitespaces?: boolean, 
})
 
 
                            
                        

@Injectable

Injectable decorator has two purposes.

One it instructs the Angular that this class needs a dependency. The Angular compiler will generate the necessary metadata to create the class’s dependencies

Second, using the providedIn we inform the Dependency Injection system how to provide the service.

                              

@Injectable({
  providedIn?: Type<any> | 'root' | 'platform' | 'any' | null
})
 
                            
                        

@Directive

@Directive Decorator marks a class as an Angular directive. The directives help us to change the appearance, behavior, or layout of a DOM element.

                              

@Directive({
  selector?: string,
  inputs?: string[],
  outputs?: string[],
  providers?: Provider[],
  exportAs?: string,
  queries?: { [key: string]: any;},
  host?: {[key: string]: string; },
  jit?: true
})
 
                            
                        

@Pipe

Decorator that marks a class as Angular Pipe and supplies configuration metadata.

                              
 
@Pipe({
  name: string,
  pure?: boolean
})
 
                            
                        

Property Decorators

Property Decorators are applied to the properties of the class.

@Input

Input decorator marks the property as the input property. I.e it can receive data from the parent component. The parent component uses the property binding to bind it to a component property. Whenever the value in the parent component changes angular updates the value in the child component.

                              

Input(bindingPropertyName?: string)
 
                            
                        

@Output

Output decorates the property as the output property. We initialize it as an EventEmitter. The child component raises the event and passes the data as the argument to the event. The parent component listens to events using event binding and reads the data.

                              

Output(bindingPropertyName?: string)
                            
                        

@ContentChild & @ContentChildren

The ContentChild & ContentChildren are decorators, which we use to Query and get the reference to the Projected Content in the DOM. Projected content is the content that this component receives from a parent component.

                              
 
ContentChild(
  selector: string | Function | Type<any> | InjectionToken<unknown>, 
  opts?: {read?: any; static?: boolean;}
)
 
                            
                        
                              

ContentChildren(
  selector: string | Function | Type<any> | InjectionToken<unknown>, 
  opts?: { descendants?: boolean;    read?: any;}
)

                            
                        

@ViewChild & @ViewChildren

The ViewChild or ViewChildren decorators are used to Query and get the reference of the DOM element in the Component. ViewChild returns the first matching element and ViewChildren returns all the matching elements as QueryList of items. We can use these references to manipulate element properties in the component.

                              
 
ViewChild(
  selector: string | Function | Type<any> | InjectionToken<unknown>, 
  opts?: {
 read?: any; static?: boolean;}
)
 
                            
                        
                              

ViewChildren(
  selector: string | Function | Type<any> | InjectionToken<unknown>, 
  opts?: {read?: any;}
)
 
                            
                        

@HostBinding

The HostBinding allows us to bind to a property of the host element. The host is an element on which we attach our component or directive. This feature allows us to manipulate the host styles

                              
 
@HostBinding(hostPropertyName?: string)
                            
                        

Method decorators

Method Decorators are applied to the methods of the class.

@HostListener

The HostListener listens to host events. The host is an element on which we attach our component or directive. Using HostListener we can respond whenever the user performs some action on the host element.

                              
 
@HostListener(eventName: string, args?: string[])
                            
                        

Parameter decorators

Parameter Decorators are applied to the constructor parameter of the class.

@Inject

The @Inject() is a constructor parameter decorator, which tells angular to Inject the parameter with the dependency provided in the given token. It is a manual way of injecting the dependency

                              

Inject(token:any)
                            
                        

@Host

The @host is a Parameter decorator that tells the DI framework to resolve the dependency in the view by checking injectors of child elements, and stop when reaching the host element of the current component.

@Self

The @Self decorator instructs Angular to look for the dependency only in the local injector. The local injector is the injector that is part of the current component or directive.

@SkipSelf

The @SkipSelf decorator instructs Angular to look for the dependency in the Parent Injector and upwards.

@Optional

@Optional marks the dependency as Optional. If the dependency is not found, then it returns null instead of throwing an error

Custom Decorators

You can also build your own custom decorators. You can refer to these articles.

  1. Inspiration for Custom Decorators in Angular
  2. Custom Decorators in Angular