It’s Time to learn the two-way binding concept in Angular two-way binding is a very useful feature, with the help of two-way binding we can synchronize the update of a property between a component and an HTML element.
In Angular, two-way binding is typically used with the [(ngModel)]
directive, which is a part of FromModule,
First You need to import a FormModule in your app.module.ts file
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FormComponent } from './_components/form/form.component';
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
FormComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule // import the FormModule from @angular/form
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
TypeScriptGoto your component file now you need to create a javascript object which has some properties like – firstName, lastName, rollName, and result.
import { Component } from '@angular/core';
import { FormData } from 'src/app/_models/form.interface';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.scss']
})
export class FormComponent {
formData: FormData = {
firstName: '',
lastName: '',
rollNumber: '',
result: ''
}
studentList: FormData[] = [];
constructor(){
}
onSubmit(){
const studentObj = {...this.formData}
this.studentList.push(studentObj)
this.formData = {
firstName: '',
lastName: '',
rollNumber: '',
result: ''
}
}
}
TypeScriptIn your HTML template (.html
file), you need to use the [(ngModel)]
directive to bind your input value to the formData.firstName
property and display.
<div>
<div class="form-group">
<label for="first_name">First Name:</label>
<input type="text" [(ngModel)]="formData.firstName" class="form-control" id="first_name">
</div>
<div class="form-group">
<label for="last_name">Last Name:</label>
<input type="text" [(ngModel)]="formData.lastName" class="form-control" id="last_name">
</div>
<div class="form-group">
<label for="roll_number">Roll Number:</label>
<input type="text" [(ngModel)]="formData.rollNumber" class="form-control" id="roll_number">
</div>
<div class="form-group">
<label for="Result">Result:</label>
<input type="text" [(ngModel)]="formData.result" class="form-control" id="Result">
</div>
<button type="submit" (click)="onSubmit()" class="btn btn-primary">Submit</button>
</div>
HTMLHappy Coding ☺️
No Comments
Leave a comment Cancel