Javascript 选中复选框并在Angular 5的帮助下将其存储在我的数据库中

Javascript 选中复选框并在Angular 5的帮助下将其存储在我的数据库中,javascript,angular,angular5,Javascript,Angular,Angular5,我想在我的项目中添加一个字段,就像我选中复选框,然后在angular 5的帮助下将其存储在数据库中一样。所以我不知道如何用angular 5编码 index.component.html <div class="billable"> <div class="bilable-label"> <label class="ct-form-label">Billable</label> </div> <div clas

我想在我的项目中添加一个字段,就像我选中复选框,然后在angular 5的帮助下将其存储在数据库中一样。所以我不知道如何用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>  

计费
多恩
所以我想知道,当我点击“完成”按钮,然后选中“存储在我的数据库中”,那么在
index.component.ts
中,我需要什么样的代码。 为简单起见,我们将使用模板驱动的表单方法:

只需将表单与onSubmit绑定(查看表单标记),如果需要,还可以在复选框中添加事件:

您的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>
有两种类型的

(一)

(二)

下面的示例显示了一个模板驱动的表单。 根据示例:

  • 用户模型和用户服务用于在数据库中存储数据
  • onFormSubmit()
    函数在表单实例提交后获取表单实例,您可以验证其值
  • 一旦值被验证并分配给模型(用户模型),然后调用服务来保存值
查看教程以获取清晰的信息-

TS组件

 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>

提交

HTML文件

<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>
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); 
}
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']));
}
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");
    });
});
Nodejs文件

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

我想在数据库中存储true,那么我需要在这段代码中添加什么呢@Rotemya@Ronak,我不确定我是否理解,但如果您真的想在数据库中存储数据,则需要设置服务器(java/node/go..etc'),并将其连接到数据库(SQL或NoSQL)。如果只想将数据存储在浏览器中-可以将其存储在本地/会话存储中-请选中此项: