Reputation: 649
I have a form contains some text boxes, select and checkbox,while submit the form I need to capture the value of all input fields in the format of {"email":"[email protected]","password":"test123","list":["one"],"groups":["group1","group2"]} and to show in a console.I have used the formsmodule of angular. Here is the code below
<form (ngSubmit)="getFormData()">
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" id="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd">
</div>
<div class="form-group">
<label for="pwd">List:</label>
<select class="form-control" id="list">
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
</select>
</div>
<div class="form-group">
<label for="pwd">Group:</label>
<input type="checkbox" name="check1" value="group1">group1
<input type="checkbox" name="check2" value="group2">group2
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
import { Component, OnInit } from '@angular/core';
import { CommonserviceService } from './../utilities/services/commonservice.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
getListData: any;
constructor(private commonserviceService: CommonserviceService) { }
ngOnInit() {
}
getFormData(){
alert('hi');
}
}
Upvotes: 0
Views: 2658
Reputation: 42526
Since you are working with Angular, I would recommend you to use reactive forms, which is natively available in Angular. As stated on the introduction to reactive forms,
Reactive forms use an explicit and immutable approach to managing the state of a form at a given point in time. Each change to the form state returns a new state, which maintains the integrity of the model between changes. Reactive forms are built around observable streams, where form inputs and values are provided as streams of input values, which can be accessed synchronously.
To achieve that, you will need to import FormsModule
and ReactiveFormsModule
onto your component's module.ts
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
FormsModule,
ReactiveFormsModule,
// other imports
],
// others
})
Then, on your component.html, you will need to bind your form to a formGroup
, and supply each input
/select
with a formControlName
<form [formGroup]="newForm" (ngSubmit)="getFormData()">
<div class="form-group">
<label for="email">Email address:</label>
<input formControlName="email" type="email" class="form-control" id="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input formControlName="password" type="password" class="form-control" id="pwd">
</div>
<div class="form-group">
<label for="pwd">List:</label>
<select formControlName="list" class="form-control" multiple>
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
</select>
</div>
<div formGroupName="groups" class="form-group">
<label for="pwd">Group:</label>
<input type="checkbox" formControlName="group1">group1
<input type="checkbox" formControlName="group2">group2
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
Then, on your component.ts, you will need to initialise your formGroup
, and handle the submit event, which will print out the values of your form.
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
newForm = this.fb.group({
email: [''],
password: [''],
list: ['one'],
groups: this.fb.group({
group1: [false],
group2: [false],
}),
});
constructor(private fb: FormBuilder) { }
getFormData() {
const res = { ...this.newForm.value };
res.groups = Object.entries(res.groups).map(item => {
if (item[1]) {
return item[0];
};
}).filter(n => n);
console.log(res);
}
}
I have created a short demo over here, but I believe you should read up more about FormBuilders, FormGroups, and FormControls on the official Angular tutorial to gain a better understanding of what you can do with Reactive Forms.
Upvotes: 1
Reputation:
You can achieve this by using either ngModel or Formgroup. I prefer Formgroup for small forms.
In your app.module.ts add the Reactive forms module
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
FormsModule,
ReactiveFormsModule,
]
})
In your app.component.html
<form [formGroup]="dataGroup">
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" formControlName="email" class="form-control" id="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" formControlName="password" class="form-control" id="pwd">
</div>
<div class="form-group">
<label for="pwd">List:</label>
<select class="form-control" formControlName="list" id="list" multiple>
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
</select>
</div>
<div class="form-group">
<label for="pwd">Group:</label>
<input type="checkbox" (change)="onCheckChange($event)" name="check1" value="group1">group1
<input type="checkbox" (change)="onCheckChange($event)" name="check2" value="group2">group2
</div>
<button type="submit" (click)="getFormData(dataGroup.value)" class="btn btn-default">Submit</button>
</form>
and in your app.component.ts
import { Component, OnInit } from '@angular/core';
import { CommonserviceService } from './../utilities/services/commonservice.service';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
getListData: any;
dataGroup: FormGroup;
selectedGroups: string[];
constructor(private commonserviceService: CommonserviceService) {
this.dataGroup = new FormGroup({
email: new FormControl(''),
password: new FormControl(''),
list: new FormControl('')
});
this.selectedGroups = [];
}
ngOnInit() {
}
onCheckChange(event) {
if (event.target.checked) {
this.selectedGroups.push(event.target.value);
} else {
const index = this.selectedGroups.findIndex(item => item === event.target.value);
if (index !== -1) {
this.selectedGroups.splice(index, 1);
}
}
}
getFormData(value){
value['groups'] = this.selectedGroups;
console.log(value);
}
}
Upvotes: 0