HTML File
<div class="form-group">
<label class="col-md-4">Hobbie</label>
<table class="table">
<tbody>
<tr>
<td *ngFor="let control of hobbiesArray.controls; let i = index">
<input class="from-check-input" [formControl]="control" (change)="getSelectedHobbies()" type="checkbox" id="inlinecheckbox{{i}}">
<label class="from-check-lable" for="inlinecheckbox{{i}}">{{studentHobbies[i]}}</label>
</td>
</tr>
</tbody>
</table>
</div>
<div class="alert alert-danger" *ngIf="studentHobbiesError && checkHobbiesTouched()">
Atleast choose one
</div>
<div class="form-group">
<button (click)="addStudentInfo()"
[disabled]="angForm.pristine || angForm.invalid || studentHobbiesError"
class="btn btn-primary">Add Student</button>
</div>
Component File
const URL = 'http://localhost:4000/api/upload';
studentHobbies: Array<String> = ['Cricket', 'Reading', 'Football', 'Tenis'];
studentHobbiesError: Boolean = true;
constructor(private fb: FormBuilder, private http: HttpClient, private ss: StudentService) {
this.createForm();
}
createForm() {
this.angForm = this.fb.group({
s_hobbie: this.addHobbies()
});
}
addHobbies() {
const hobbieArrays = this.studentHobbies.map(element => {
return this.fb.control(false);
});
return this.fb.array(hobbieArrays);
}
get hobbiesArray() {
return <FormArray>this.angForm.get('s_hobbie');
}
getSelectedHobbies() {
this.selectedHobbies = [];
this.hobbiesArray.controls.forEach((control, i) => {
if (control.value) {
this.selectedHobbies.push(this.studentHobbies[i]);
}
});
this.studentHobbiesError = this.selectedHobbies.length > 0 ? false : true;
}
checkHobbiesTouched() {
let flg = false;
this.hobbiesArray.controls.forEach((control) => {
if (control.touched){
flg = true;
}
});
return flg;
}
addStudentInfo() {
const newHobbie = this.selectedHobbies;
this.ss.addStudent(newHobbie);
}
Service File
uri = 'http://localhost:4000/student';
addStudent(s_hobbie) {
const obj = {
s_hobbie: s_hobbie
};
console.log(obj);
this.http.post(`${this.uri}/add`, obj)
.subscribe(res => this.router.navigate(['/student']));
}
Nodejs File
const express = require('express');
const app = express();
const studentRoutes = express.Router();
studentRoutes.route('/add').post(function (req, res) {
let student = new Student(req.body);
student.save()
.then(student => {
res.status(200).json({'student': 'student in added successfully'});
})
.catch(err => {
res.status(400).send("unable to save to database");
});
});