Angular Forms, Pipes, and Services
Angular Forms, Pipes, and Services
Angular Forms
Angular provides two approaches for handling user input: Template-Driven Forms and Reactive Forms.
Template-Driven Forms are simple to build and are ideal for beginners or small forms. Form logic is defined mainly in the HTML template using the ngModel directive.
<form #myForm="ngForm" (ngSubmit)="onSubmit()">
<input
type="email"
name="email"
[(ngModel)]="userEmail"
placeholder="Enter your email"
required
>
<button type="submit">Submit</button>
</form>
Reactive Forms provide greater control over validation and dynamic form creation. The form structure is defined inside the TypeScript component.
import { FormGroup, FormControl, Validators } from '@angular/forms';
loginForm = new FormGroup({
email: new FormControl('', [Validators.required, Validators.email]),
password: new FormControl('', [
Validators. required,
Validators.minLength(8)
])
});
Pipes
Pipes transform data before displaying it in the template without changing the original value.
<p>{{ 'guvi courses' | uppercase }}</p>
<p>{{ today | date:'dd/MM/yyyy' }}</p>
<p>{{ price | currency:'INR' }}</p>
<p>{{ longText | slice:0:100 }}</p>
<p>{{ 3.14159 | number:'1.2-2' }}</p>
<p>{{ courseName | uppercase | slice:0:10 }}</p>
Built-in pipes such as uppercase, date, currency, slice, and number help format data quickly without writing additional logic.
Services and Dependency Injection
Services allow you to keep reusable business logic separate from UI components.
Create a service.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class CourseService {
getCourses() {
return [
'Angular',
'React',
'Node.js',
'Python',
'MongoDB'
];
}
}
Use the service inside a component.
import { Component, OnInit } from '@angular/core';
import { CourseService } from './course.service';
@Component({
selector: 'app-course-list',
standalone: true,
templateUrl: './course-list.html'
})
export class CourseListComponent implements OnInit {
courses: string[] = [];
constructor(private courseService: CourseService) {}
ngOnInit(): void {
this.courses = this.courseService.getCourses();
}
}
Dependency Injection automatically creates and provides the service whenever a component requests it, making the application modular and easier to maintain.










