Understanding Observables and Directives

Kasun Weerasinghe
3 min readJul 10, 2024

--

Mastering Angular (Part I)

Introduction

Angular is a powerful framework for building dynamic web applications. Two core concepts that every Angular developer should master are Observables and Directives. This article will dive into these concepts, exploring their importance, use cases and practical examples.

Understanding Observables in Angular

Observables are a key part of reactive programming in Angular. They allow you to manage asynchronous data streams effectively.

What are Observables?

An Observable is a data producer that can emit multiple values over time. Observables are part of the RxJS library, which is bundled with Angular. They are essential for handling asynchronous operations like HTTP requests, user input events, etc.

Creating and Subscribing to Observables

Let’s look at a simple example of creating and subscribing to an Observable.

import { Observable } from 'rxjs';

const observable = new Observable(observer => {
observer.next('Hello, Observable!');
observer.complete();
});

observable.subscribe({
next: value => console.log(value),
complete: () => console.log('Observable completed')
});

In this example, we create an Observable that emits a single value and then completes. The subscribe method is used to listen to the emitted values.

Using Observables with HTTPClient

One of the most common uses of Observables in Angular is making HTTP requests. The HttpClient service returns Observables, making it easy to work with asynchronous data.

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';

@Component({
selector: 'app-data',
template: `<div *ngIf="data">{{ data }}</div>`
})
export class DataComponent implements OnInit {
data: any;

constructor(private http: HttpClient) {}

ngOnInit() {
this.http.get('https://api.example.com/data')
.subscribe(response => this.data = response);
}
}

In this example, we use HttpClient to make a GET request to an API and subscribe to the Observable to handle the response.

Exploring Directives in Angular

Directives are another crucial concept in Angular. They allow you to extend the HTML by adding new behavior to elements and components.

What are Directives?

Directives are classes that add additional behavior to elements in your Angular applications. There are three types of directives in Angular:

  • Component Directives: Directives with a template.
  • Structural Directives: Directives that change the DOM layout by adding and removing DOM elements.
  • Attribute Directives: Directives that change the appearance or behavior of an element, component, or another directive.

Creating a Custom Directive

create a simple attribute directive that changes the background color of an element.

import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';

@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {

constructor(private el: ElementRef, private renderer: Renderer2) {}

@HostListener('mouseenter') onMouseEnter() {
this.highlight('yellow');
}

@HostListener('mouseleave') onMouseLeave() {
this.highlight(null);
}

private highlight(color: string) {
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', color);
}
}

In this example, the HighlightDirective listening mouse enters and leaves events to change the background color of the host element.

Understanding Observables and Directives is essential for building robust and efficient Angular applications. Observables allow you to handle asynchronous data streams seamlessly, while Directives let you extend HTML with custom behavior.

--

--

Kasun Weerasinghe
Kasun Weerasinghe

Written by Kasun Weerasinghe

Hi there! 👋 I'm Kasun, Front-End Developer. With a deep love for technology and innovation.

No responses yet