← Back to list

Understanding Angular: Component, Directive, Pipe, Service, and DI

Everything is angular is a ‘component’. What are those can be?

Melih · 2025-02-23 16:43 · 1 claps · 3.0 min read
#angular #directives-in-angular #pipes-in-angular #services-in-angular #angular-components
Open on Medium ↗
Wiki topics: 🌐 · Web Development

Understanding Angular: Component, Directive, Pipe, Service, and DI

Everything is angular is a ‘component’. What are those can be?

First of all we should understand concepts of decorators. ‘@’ means a lot for us because ‘@’ will decorate our different components.

  1. @Component

A Component is a building block of Angular. It combines HTML, CSS, and TypeScript in one entity. A component is created using the @Component decorator.

@import {Component} from '@angular/core'

@Component({
  selector: 'comp-name-to-use-in-project'
  templateURL: './html-file-address'
  styleUrls: './design-file-address'
})

export class MyComponent {
  title: 'hello angular'
}
  1. @Directive

Directives allow us to perform custom operations on the DOM. There are two types of directives:

There is two different directives. One of them is structural directives which modifies HTML (DOM) structure. Second one is attribute directives which modifies elements view. Besides these, additionally we can make our directives for our needs.

2.1 Structural Directives

Structural Directives: These modify the HTML (DOM) structure. Common examples include ngIf, ngFor, and ngSwitch.

Example of ngIf and ngFor:

<div *ngIf="isVisible"> make this div visible on if statement true</div>
<ul>
  <li *ngFor="let item of items">{{item}} is in screen</li>
</ul>

2.2 Attribute Directives

Attribute Directives: These modify the appearance or behavior of an element. They are usually written with square brackets []. Common examples include ngStyle, ngClass, and custom styles.

Example of ngStyle:

<div [style.color]="isActive ? 'green' : 'red' "></div>

2.3 Custom Directives

We can create custom directives for our needs.

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

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

export class HighlightDirective {
@Input highlightColor: string = 'yellow';

constructor(private el: ElementRef) {}

@HostListener('mouseenter') onMouseEnter() {
  this.el.nativeElement.style.backgroundColor = this.highlighterColor;
}

@HostListener('mouseleave') onMouseLeave() {
    this.el.nativeElement.style.backgroundColor = null;
  }
}
<p appHighlight highlightColor='red'>hover will change the color to red.</p>

As an extra we can make our own structural directive with ViewContainerRef and TemplateRef

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[appMyIf]'
})
export class MyIfDirective {
  @Input() set appMyIf(condition: boolean) {
    if (condition) {
      this.viewContainer.createEm  beddedView(this.templateRef);
    } else {
      this.viewContainer.clear();
    }
  }

  constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {}
}
<div *appMyIf="showElement">Bu element görünür.</div>
  1. Pipe

Angular pipes for convert or format data flow such as filtering, uppercase etc.

import { Pipe } from '@angular/core'

@Pipe({
  name: 'reverseString'
  pure: true
})

export class ReverseStringPipe implements PipeTransform {
  transform(value: string): string { //improves data
    return value.split('').reverse().join('');
  }
}
<p>{{ 'Angular' | reverseString | can have parameter here}}</p>

3.1 Pure and Impure Pipes

In giving example I added true (which is true as default, no need, i added to show) for make pure pipe. So what is impure pipe? Impure pipe is triggers in every changes in our component (change detection is laters topic). When we need it? If we working with changable (async) data, we should use it. For example if you have an array and if you add or remove elements to the array, you should use impure pipe, otherwise your array render one time in the beginning and new changes will never be on screen.

For more example of impure pipes, you can read aboyt async pipe.

  1. Service and Dependency Injection (DI)

Service is a class that provides a specific functionality or logic that can be shared across components or other services.

DI is a design pattern used in Angular to manage how dependencies (like services) are provided to components, directives, or other services.

import { Injectable } from '@angular/core'
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  provideIn: 'root' // This makes the service available throughout the app
})

export class DataService {
  private apiUrl = 'https://api.example.com/data'

  constructor(private http: HttpClient) {}

  getData(): Observable<any[]>{
    return this.http.get<any>(this.apiUrl);  
  }
}

The @Injectable() decorator marks the class as a service that can be injected into components or other services.

Usage in component

// app.component.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'app-root',
  template: `<h1>Data from API</h1><pre>{{ data | json }}</pre>`,
})
export class AppComponent implements OnInit {

  data: any;

  constructor(private dataService: DataService) {}

  ngOnInit() {
    this.dataService.getData().subscribe(response => {
      this.data = response;
    });
  }
}

The AppComponent class uses Dependency Injection to get an instance of the DataService.

How DI works:

  1. Injector: Angular has an injector that is responsible for creating and managing the lifecycle of services. When you declare a service in a component’s constructor, Angular’s DI system automatically looks up the service in the injector and provides it to the component.

  2. Scope of DI: The service can be provided in different scopes. If you use providedIn: ‘root’, it will be a singleton throughout the application. If you provide it in a component or module, it will be created and available only within that component or module’s scope.


메타데이터
post_id
1df2c1c56991
slug
understanding-angular-component-directive-pipe-service-and-di-1df2c1c56991
url
https://medium.com/@barisik.melih/understanding-angular-component-directive-pipe-service-and-di-1df2c1c56991
canonical_url
https://medium.com/@barisik.melih/understanding-angular-component-directive-pipe-service-and-di-1df2c1c56991
author_url
https://medium.com/@barisik.melih
status
ok
fetched_at
2026-07-17 18:16:58