0

I want to add one field in my project which is like when I check my checkbox then it store in my database with the help of angular 5. So I don't know how to code it with angular 5.

index.component.html

<div class="billable">
  <div class="bilable-label">
    <label class="ct-form-label">Billable</label>
  </div>
  <div class="billable-checkbox">
    <input type="checkbox" [name]="billable" (click)="Billable()" />
  </div>
</div>
<button mat-button class="ct-submit mat-button" (click)="submit()" [disabled]="entryTimeForm.invalid || isRequestLoading || !currentTimeEntry.projectId">
  Done
</button>  

So I want like when i click on Done button then checked store in my db so what kind of code do i need for that in index.component.ts

3 Answers 3

1

There are two types of forms

1) Template Driven Forms

2) Model Drive Reactive Forms

The example below shows a template driven form. According to the example:

  • A User model and a user service are used for storing data in the database.
  • onFormSubmit() functions get the form instance once it gets submitted and you could verify for values.
  • Once values are verified and assigned to model (User model) then call the service to save the value

Check the tutorial for clear information - Link

TS Component

 export class TemplateDrivenFormComponent { 
        user = new User();
        constructor(private userService: UserService) {
        }
        onFormSubmit(form: NgForm) {

           if(form.invalid){
              return;   
           }    

           this.user.isMarried = form.controls['married'].value;
           // assign other values and form the user object
           this.userService.createUser(this.user); // then call the service to store data
        }
}

HTML

<form #userForm="ngForm" (ngSubmit)="onFormSubmit(userForm)">
  <input type="checkbox" name="married" [ngModel]="user.isMarried">
  <button>Submit</button>
</form>
Sign up to request clarification or add additional context in comments.

Comments

0

There you go. For simplicity we'll use a template driven form approach:

You simply bind a form with onSubmit (look at the form tag) and if you want you can add event on the checkbox as well:

Your index.component.html:

<div class="index-component-class">
  <form  (ngSubmit)="onSubmit()">
    <div class="billable">
      <div class="bilable-label">
        <label class="ct-form-label">Billable</label>
      </div>
      <div class="billable-checkbox">
        <input type="checkbox" [name]="billable" (change)="checkboxClicked()" [(ngModel)]="checkboxValue" />
      </div>
    </div>
  <button type="submit"  class="ct-submit"> Done</button>
  </form>
</div>

Your index.component.ts:

import {Component, OnDestroy, OnInit} from '@angular/core';
import {Subscription} from 'rxjs/Subscription';
import {MyHttpService}   from '../../../core/http/myHttp.service';

@Component({
  selector    : 'index-component',
  templateUrl : './index-component.html',
  styleUrls   : ['./index-component.scss'],
})
export class IndexComponent implements OnInit, OnDestroy {

  private sub   : Subscription;
  checkboxValue : boolean;

  constructor(private _myHttpService: MyHttpService) {
  }

  ngOnInit() {
    //Add some setup if you need..
  }

  onSubmit(){
   if(checkboxValue){
     //Go to server
     this._myHttpService.saveInDatabase().subscribe(params => {
       //Decide what you want to to..
     });
   }
  }


  checkboxClicked() {
    //Decide what you want to to..
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }

}

2 Comments

i want to store true in database so what can should i need to add in this code @Rotemya
@Ronak, Not sure i understood, but if you want to really store data in a database, you need to setup a server (java /node/go..etc'), and hook it up to a database (SQL or NoSQL). If you want to simply store data in the browser - you can store it on local / session storage - check this: stackoverflow.com/questions/2010892/…
0

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");
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.