Step 1: Create a New Angular Project
ng new reactiveform
cd reactiveform
code .
Step 2: Create a Reactive Form
Modify app.component.ts
to import necessary modules:
import { Component } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms';
@Component({
selector: 'app-root',
imports: [ReactiveFormsModule],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent {
profileForm = new FormGroup({
name: new FormControl('RMC'),
password: new FormControl('098765'),
email: new FormControl(),
mobile: new FormControl(),
})
submitData() {
console.log(this.profileForm.value.name);
}
setValues() {
this.profileForm.setValue({
name: 'Peter',
password: '12345121212',
email: 'a123@a.com',
mobile: '123456789'
})
}
}
Step 3: Modify app.component.html
to Create the Form
<h1>Basic React Form</h1><form [formGroup]="profileForm"><label>Name: </label><br><input type="text" placeholder="Enter your name" formControlName="name"><br><br><label>Password: </label><br><input type="text" placeholder="Enter your password" formControlName="password"><br><br><label>email: </label><br><input type="text" placeholder="Enter your email" formControlName="email"><br><br><label>Mobile: </label><br><input type="text" placeholder="Enter yourMobile" formControlName="Mobile"><br><br><button (click) = 'submitData()'>Submit</button><br><button type="button" (click) = 'setValues()'>SetData</button><br></form><hr>Check: {{this.profileForm.value.name}}
🚀 Summary
- We created a reactive form using Angular Material.
- 🎉 Congratulations! You just built an reactive basic Form! Keep experimenting! 💡
No comments:
Post a Comment