Angular offers robust tools for building forms and
integrating with APIs. This chapter delves into:
1. Angular Forms Overview
Angular provides two primary approaches to handling forms:
|
Feature |
Template-driven
Forms |
Reactive Forms |
|
Approach |
Declarative (in
templates) |
Imperative (in
component class) |
|
Form Creation |
Defined in
the template using directives |
Defined in
the component using APIs |
|
Data Binding |
Two-way binding with [(ngModel)] |
Unidirectional binding
using FormControl |
|
Validation |
Template-based |
Programmatic |
|
Use Case |
Simple forms |
Complex forms with
dynamic behavior |
2. Template-driven Forms
Template-driven forms are suitable for simple scenarios and
rely heavily on Angular's directives.
Setting Up
typescript
import
{ FormsModule } from '@angular/forms';
typescript
@NgModule({
imports: [FormsModule]
})
Creating a Form
html
<form
#userForm="ngForm" (ngSubmit)="onSubmit(userForm)">
<label for="name">Name:</label>
<input id="name" name="name"
ngModel required>
<label for="email">Email:</label>
<input id="email" name="email"
ngModel email>
<button type="submit">Submit</button>
</form>
Handling Submission
typescript
onSubmit(form:
NgForm) {
console.log(form.value);
}
3. Reactive Forms
Reactive forms provide more control and are suitable for
complex scenarios.
Setting Up
typescript
import
{ ReactiveFormsModule } from '@angular/forms';
typescript
@NgModule({
imports: [ReactiveFormsModule]
})
Creating a Form
typescript
import
{ FormGroup, FormControl, Validators } from '@angular/forms';
userForm
= new FormGroup({
name: new FormControl('', Validators.required),
email: new FormControl('', [Validators.required,
Validators.email])
});
Template
html
<form
[formGroup]="userForm" (ngSubmit)="onSubmit()">
<label for="name">Name:</label>
<input id="name" formControlName="name">
<label for="email">Email:</label>
<input id="email" formControlName="email">
<button type="submit">Submit</button>
</form>
Handling Submission
typescript
onSubmit()
{
console.log(this.userForm.value);
}
4. Form Validation
Angular provides built-in validators and allows custom
validators.
Built-in Validators
|
Validator |
Purpose |
|
Validators.required |
Ensures the field is
not empty |
|
Validators.email |
Validates
email format |
|
Validators.minLength |
Checks minimum length |
|
Validators.maxLength |
Checks
maximum length |
Custom Validator Example
typescript
function
forbiddenNameValidator(control: FormControl): ValidationErrors | null {
const forbidden = /admin/.test(control.value);
return forbidden ? { forbiddenName: { value:
control.value } } : null;
}
5. Angular HTTP Client
Angular's HttpClient allows communication with backend
services.
Setting Up
typescript
import
{ HttpClientModule } from '@angular/common/http';
typescript
@NgModule({
imports: [HttpClientModule]
})
Making HTTP Requests
typescript
import
{ HttpClient } from '@angular/common/http';
constructor(private
http: HttpClient) {}
getData()
{
this.http.get('https://api.example.com/data')
.subscribe(response => console.log(response));
}
6. API Integration
Integrating Angular with APIs involves creating services to
handle HTTP requests.
Creating a Service
bash
ng
generate service data
Service Implementation
typescript
import
{ HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root' })
export
class DataService {
constructor(private http: HttpClient) {}
fetchData() {
return this.http.get('https://api.example.com/data');
}
}
Using the Service in a Component
typescript
constructor(private
dataService: DataService) {}
ngOnInit()
{
this.dataService.fetchData()
.subscribe(data => this.data = data);
}
7. Handling HTTP Errors
Use RxJS's catchError operator to handle errors.
typescript
import
{ catchError } from 'rxjs/operators';
import
{ throwError } from 'rxjs';
this.http.get('https://api.example.com/data')
.pipe(
catchError(error => {
console.error('Error:', error);
return throwError(() => new Error('Something
went wrong'));
})
)
.subscribe();
8. HTTP Interceptors
Interceptors can modify requests or responses globally.
Creating an Interceptor
typescript
import
{ HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';
@Injectable()
export
class AuthInterceptor implements HttpInterceptor {
intercept(req:
HttpRequest<any>, next: HttpHandler) {
const cloned = req.clone({
headers: req.headers.set('Authorization',
'Bearer token')
});
return next.handle(cloned);
}
}
Providing the Interceptor
typescript
providers:
[
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor,
multi: true }
]
9. Displaying API Data in Templates
Use Angular's *ngFor directive to display lists.
html
<ul>
<li *ngFor="let item of data">
{{ item.name }}
</li>
</ul>
10. Summary
|
Feature |
Description |
|
Forms |
Collect user input |
|
Template-driven Forms |
Simple forms
using directives |
|
Reactive Forms |
Complex forms with
explicit control |
|
HttpClient |
Communicate
with backend services |
|
API Integration |
Connect Angular to
external APIs |
|
Interceptors |
Modify HTTP
requests/responses globally |
A: Yes, but having a basic understanding of TypeScript and JavaScript ES6 will help a lot.
A: Angular uses TypeScript, which is a superset of JavaScript.
A: AngularJS (1.x) is the older version using JavaScript, while Angular (2+) uses TypeScript and a component-based architecture.
A: Yes, with frameworks like Ionic or NativeScript.
A: Angular is a full framework with built-in tools, while React is a library focused on UI.
A: Yes, Angular excels in large, structured, maintainable apps.
A: It’s a command-line tool that helps scaffold, develop, and manage Angular applications efficiently.
A: Yes, Node.js is required to install Angular CLI and manage dependencies.
A: A reusable unit of UI that consists of a template, logic, and styling.
A: Yes, Angular can be paired with any backend via APIs.
Tutorials are for educational purposes only, with no guarantees of comprehensiveness or error-free content; TuteeHUB disclaims liability for outcomes from reliance on the materials, recommending verification with official sources for critical applications.
Kindly log in to use this feature. We’ll take you to the login page automatically.
LoginReady to take your education and career to the next level? Register today and join our growing community of learners and professionals.
Your experience on this site will be improved by allowing cookies. Read Cookie Policy
Your experience on this site will be improved by allowing cookies. Read Cookie Policy
Comments(0)