Introduction to Angular Annotations

Ben @Remoteman
4 min readNov 15, 2024

--

As a developer with years of experience building dynamic and scalable web applications, I’ve always been fascinated by the magic of Angular. Early in my career, I found annotations intimidating — those little @ symbols seemed mysterious and complex. But once I started to understand their purpose and power, they became one of my favorite features of Angular.

In this blog, I want to share everything I’ve learned about Angular annotations, from the basics to advanced concepts. Whether you’re a beginner just getting started or an experienced developer looking to deepen your knowledge, I hope this guide helps you harness the full potential of Angular.

I’ll also show you how to put these annotations into practice by building small projects, so you can see how they work in real-world scenarios. Let’s demystify Angular annotations together and make them a tool you’ll love to use!

Angular Annotations/Decorators

Understanding Angular Annotations: A Complete Guide

Angular provides several built-in annotations, also known as decorators, that enable developers to define metadata for components, directives, services, and other constructs. These annotations form the backbone of Angular applications, making it easier to build modular, reusable, and scalable code.

In this article, we’ll explore the key Angular annotations with examples to help you get started.

  1. @Component
    The `@Component` decorator is the building block of an Angular application. It defines a component and provides metadata like its selector, template, and styles.

Example:

import { Component } from '@angular/core';
@Component({
selector: 'app-root', // Custom HTML tag for the component
template: `<h1>Welcome to Angular!</h1>`, // Inline HTML template
styles: [`h1 { color: blue; }`] // Inline styles
})
export class AppComponent {
title = 'Angular App';
}

Here, `app-root` is the selector used in the HTML to render this component.

2. `@Directive`
The `@Directive` decorator is used to create custom directives, allowing developers to add or modify behavior to existing DOM elements.

Example:

import { Directive, ElementRef, Renderer2 } from '@angular/core';
@Directive({
selector: '[appHighlight]' // Attribute selector
})
export class HighlightDirective {
constructor(el: ElementRef, renderer: Renderer2) {
renderer.setStyle(el.nativeElement, 'backgroundColor', 'yellow');
}
}

Usage in HTML:

<p appHighlight>This text will have a yellow background.</p>

This directive highlights the text background in yellow.

3. `@Injectable`
The `@Injectable` decorator marks a class as a service that can be injected into components or other services using Angular’s **Dependency Injection** mechanism.

Example:

import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root' // Makes the service available application-wide
})
export class DataService {
getData() {
return ['Angular', 'React', 'Vue'];
}
}

This service can now be injected into any component or service in the app.

4. `@Input`
The `@Input` decorator is used to pass data from a parent component to a child component.

Example:

import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: `<p>Child component: {{ data }}</p>`
})
export class ChildComponent {
@Input() data!: string; // Property to receive data from the parent
}

Parent Component Usage:

<app-child [data]="'Hello from parent!'"></app-child>

5. `@Output`
The `@Output` decorator allows a child component to emit events to its parent, enabling two-way communication.

Example:

import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-child',
template: `<button (click)="sendMessage()">Click me</button>`
})
export class ChildComponent {
@Output() messageEvent = new EventEmitter<string>();
sendMessage() {
this.messageEvent.emit('Message from child!');
}
}

Parent Component Usage:

<app-child (messageEvent)="receiveMessage($event)"></app-child>

6. `@NgModule`
The `@NgModule` decorator defines an Angular module, which groups related components, directives, and services together.

Example:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent], // Declare components in this module
imports: [BrowserModule], // Import other Angular modules
providers: [], // Services available to the module
bootstrap: [AppComponent] // The root component to bootstrap
})
export class AppModule {}

7. `@HostListener`
The `@HostListener` decorator listens to DOM events on the host element of a directive or component.

Example:

import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[appClick]'
})
export class ClickDirective {
@HostListener('click') onClick() {
alert('Element clicked!');
}
}

Usage in HTML:

<div appClick>Click me!</div>

When you click on the element, an alert box will appear.

8. `@HostBinding`
The `@HostBinding` decorator binds a property of the host element to a directive.

Example:

import { Directive, HostBinding } from '@angular/core';
@Directive({
selector: '[appToggle]'
})
export class ToggleDirective {
@HostBinding('class.active') isActive = false;
toggleActive() {
this.isActive = !this.isActive;
}
}

Usage in HTML:

<div appToggle>Toggle class</div>

This directive dynamically toggles the `active` class on the host element.

9. `@Pipe
The `@Pipe` decorator is used to create custom pipes that transform data in templates.

Example:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'capitalize'
})
export class CapitalizePipe implements PipeTransform {
transform(value: string): string {
return value.charAt(0).toUpperCase() + value.slice(1);
}
}

Usage in HTML:

<p>{{ 'angular' | capitalize }}</p>

This pipe capitalizes the first letter of the input string.

Conclusion:
These Angular annotations allow developers to define and organize their applications efficiently. By understanding and mastering these decorators, you can create robust, reusable, and scalable Angular apps.

If you found this guide helpful, don’t forget to clap 👏 and share it with fellow developers. Happy coding! 😊

--

--

Ben @Remoteman
Ben @Remoteman

Written by Ben @Remoteman

0 Followers

Java Developer | Azure| Typescript 8+ yrs building scalable systems. Expert in microservices, APIs & cloud tech. connect: dmohammad.subhan-studios.com

No responses yet