【问题标题】:Checkbox is checked and store it in my database with the help of Angular 5在 Angular 5 的帮助下选中复选框并将其存储在我的数据库中
【发布时间】:2018-08-02 10:28:08
【问题描述】:

我想在我的项目中添加一个字段,就像我选中复选框然后它在 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 中使用什么样的代码

【问题讨论】:

    标签: javascript angular angular5


    【解决方案1】:

    forms有两种类型

    1)Template Driven Forms

    2)Model Drive Reactive Forms

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

    • 用户模型和用户服务用于在数据库中存储数据。
    • onFormSubmit() 函数在表单实例提交后获取它,您可以验证其值。
    • 验证值并分配给模型(用户模型)后,调用服务来保存值

    查看教程以获得清晰的信息 - Link

    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>
    

    【讨论】:

      【解决方案2】:

      给你。 为简单起见,我们将使用模板驱动的表单方法:

      您只需使用 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>
      

      你的 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();
        }
      
      }
      

      【讨论】:

      • 我想将 true 存储在数据库中,所以我需要在此代码中添加什么@Rotemya
      • @Ronak,我不确定我是否理解,但如果你想真正将数据存储在数据库中,你需要设置一个服务器(java /node/go..etc'),并将其连接起来到数据库(SQL 或 NoSQL)。如果您只想将数据存储在浏览器中 - 您可以将其存储在本地/会话存储中 - 请检查:stackoverflow.com/questions/2010892/…
      【解决方案3】:

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

      Nodejs 文件

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-03-23
        • 2013-07-08
        • 2018-09-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多