ලියාපදිංචි වීමේ (sign-up) සිට දත්ත ඇතුළත් කිරීම දක්වා ඕනෑම web යෙදුමක අනිවාර්ය අංගයක් වන forms, Angular හිදී නිර්මාණය කරන ප්රධාන ක්රම දෙක පිළිබඳව ඉගෙන ගනිමු.
Angular හි forms නිර්මාණය කිරීමට ප්රධාන ප්රවේශ දෙකක් ඇත:
මෙය භාවිතා කිරීමට `app.module.ts` වෙත `FormsModule` import කළ යුතුය.
<!-- contact-form.component.html -->
<form #contactForm="ngForm" (ngSubmit)="onSubmit(contactForm)">
<div class="mb-3">
<label for="name" class="form-label">Name</label>
<input
type="text"
class="form-control"
id="name"
name="name"
ngModel
required
#name="ngModel">
<div *ngIf="name.invalid && name.touched" class="text-danger">
Name is required.
</div>
</div>
<button type="submit" class="btn btn-primary" [disabled]="contactForm.invalid">Submit</button>
</form>
// contact-form.component.ts
import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';
@Component({ ... })
export class ContactFormComponent {
onSubmit(form: NgForm) {
console.log('Form Submitted!', form.value);
}
}
මෙය භාවිතා කිරීමට `app.module.ts` වෙත `ReactiveFormsModule` import කළ යුතුය.
// profile-editor.component.ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({ ... })
export class ProfileEditorComponent implements OnInit {
profileForm: FormGroup;
ngOnInit() {
this.profileForm = new FormGroup({
firstName: new FormControl('', Validators.required),
lastName: new FormControl(''),
});
}
onSubmit() {
console.log(this.profileForm.value);
}
}
<!-- profile-editor.component.html -->
<form [formGroup]="profileForm" (ngSubmit)="onSubmit()">
<div class="mb-3">
<label for="firstName" class="form-label">First Name</label>
<input type="text" id="firstName" class="form-control" formControlName="firstName">
</div>
<!-- Error handling can be done here by checking profileForm.get('firstName').invalid -->
<button type="submit" class="btn btn-primary" [disabled]="!profileForm.valid">Submit</button>
</form>
Angular මගින් පරිශීලකයා ඇතුළත් කරන දත්ත නිවැරදිදැයි පරීක්ෂා කිරීමට built-in validators සපයයි.
Reactive forms වලදී මේවා `Validators` class එකෙන් ලබා දෙන අතර, අපට අවශ්ය පරිදි Custom Validators සහ Async Validators (උදා: username එකක් server එකේ තිබේදැයි පරීක්ෂා කිරීම) ද නිර්මාණය කළ හැකිය.