Decorators

Learn about the purpose of decorators, their different types, and how to use them in an Ionic application.

Let’s move on to the next main element of the home.page.ts file.

Press + to interact
import { Component } from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
constructor() {}
}

After the import statement on line 1, we can see the following lines of code, known as a decorator:

@Component({
    selector: 'app-home',
    templateUrl: 'home.page.html',
    styleUrls: ['home.page.scss'],
})

What is a decorator?

The role of a decorator, which accompanies every class created in an Ionic-Angular application (and always sits above the class), is to provide metadata for the class itself.

Decorators can declare a variety of metadata such as:

  • The page selector
  • The URL to the template this class will use
  • Which providers, directives and pipes that the class might use

The decorator in the above example declares that the class is a component and contains metadata concerning the template, styles, and CSS selector the class will use.

Note: Any components, directives, pipes, or services declared in the decorator first have to be imported into the script through an import statement towards the top of the file.

Types of decorators

Decorators used within Ionic come in a few different types:

  • The @Component decorator
  • The @Directive decorator
...