Day 3: Core Concepts of Angular
Dipak Ahirav
Posted on May 4, 2024
🚀 Check Out My YouTube Channel! 🚀
Hi everyone! If you enjoy my content here on Dev.to, please consider subscribing to my YouTube channel devDive with Dipak. I post practical full-stack development videos that complement my blog posts. Your support means a lot!
In the previous two days, we set up our Angular development environment and got a high-level introduction to the framework. Today, we'll dive deeper into the core concepts of Angular, which form the foundation of any Angular application.
1. Components
At the heart of every Angular application are components. A component in Angular consists of a TypeScript class, an HTML template, and associated styles. It serves as the building block of the UI, encapsulating the data, layout, and behavior of a part of the webpage. Each component is responsible for a specific screen area and functions independently, promoting reusability and modularity.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Hello Angular';
}
2. Modules
Angular organizes code into modules. Modules in Angular are used to group related components, services, and other artifacts together. Modules help organize the application's codebase and enable lazy loading, which can improve the application's performance.
The root module, AppModule, is the entry point of the application, and other modules can be imported and used within it. The NgModule
decorator provides the metadata that Angular needs to compile component templates and inject dependencies.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
3. Templates
Templates define the views of an Angular application. They are written with HTML that contains Angular-specific elements and attributes. These templates are designed to leverage Angular's two-way data binding, event handling, and various directives.
<div>
<h1>{{ title }}</h1>
<button (click)="doSomething()">Click me</button>
</div>
4. Data Binding
Data binding in Angular helps in synchronizing data between the model and view components. Angular provides several types of data binding:
-
Interpolation:
{{ value }}
- Bind component data into the HTML. -
Property Binding:
[property]="value"
- Bind properties of DOM elements. -
Event Binding:
(event)="handler()"
- Handle user events. -
Two-way Binding:
[(ngModel)]="property"
- Combine property and event binding.
5. Dependency Injection
Dependency Injection (DI) is a core concept in Angular that allows classes to receive dependencies from external sources rather than creating them internally. Angular's DI framework provides declared dependencies to classes when they are instantiated, making your code more modular and easy to manage.
DI promotes loose coupling, testability, and maintainability by allowing you to easily swap out implementations.
6. Services and DI
Services are singleton objects that Angular creates for shared or reusable data or functions. These are typically injected into components using Angular's dependency injection system, making them a powerful way to write less code while doing more.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
getData() {
return ['data1', 'data2', 'data3'];
}
}
Injecting Services into Components
To use a service in a component, you must first import it and then include it in the constructor of your component class. Angular takes care of creating an instance of the service and provides it to the component at runtime.
import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-data-component',
templateUrl: './data-component.component.html',
styleUrls: ['./data-component.component.css']
})
export class DataComponent implements OnInit {
data: string[];
constructor(private dataService: DataService) {}
ngOnInit() {
this.data = this.dataService.getData();
}
}
7. Directives
Directives are classes that add additional behavior to elements in your Angular applications. They come in three forms:
- Components: Directives with a template.
- Structural directives: Change the DOM layout by adding and removing DOM elements, such as *ngIf and *ngFor..
- Attribute directives: Change the appearance or behavior of an element, component, or another directive, such as ngClass and ngStyle.
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}
8. Pipes
Pipes are simple functions in Angular that you can use in template expressions to accept an input value and return a transformed value. Pipes are particularly useful for formatting strings, currency amounts, dates, and other display data. Angular provides several built-in pipes and also allows you to create custom pipes.
Using Built-in Pipes
<!-- Date Pipe -->
<p>{{ today | date:'fullDate' }}</p>
<!-- Currency Pipe -->
<p>{{ amount | currency:'USD':'symbol' }}</p>
<!-- Custom Pipe for transforming text -->
<p>{{ message | capitalize }}</p>
Creating Custom Pipes
To create a custom pipe, you define a pipe class and annotate it with the @Pipe
decorator. The pipe class implements the PipeTransform
interface's transform
method that takes an input value and optional parameters and returns the transformed value.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'capitalize'})
export class CapitalizePipe implements PipeTransform {
transform(value: string): string {
if (value) {
return value.charAt(0).toUpperCase() + value.slice(1);
}
return value;
}
}
This custom Capitalize
pipe would take any string value and capitalize the first letter of the string, making it easy to handle text transformations directly within your templates.
Conclusion
By understanding and implementing these core concepts in Angular with code examples, you are now equipped to start building more complex and feature-rich Angular applications. In the next blog post, we will explore Routing and Navigation in Angular, which is essential for creating dynamic and interactive single-page applications.
Happy coding!
Posted on May 4, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.