如何根据用户输入为角度复选框设置二进制值?

时间:2018-12-17 16:16:00

标签: angular

我是Angular的新手,我正在尝试在此link之后建立一个简单的注册页面。我需要根据用户是否接受条款和条件发送emailid,用户名,密码和1/0值。

我正在使用一个复选框来检测用户是否已接受条款和条件。

问题是Angular向api发送了一个true / false值,而api则期望值为1/0。

我尝试使用isChecked变量设置值。在html中可以正确设置该值,但是在提交表单时,它仍会发送true / false值。

component.ts:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { first } from 'rxjs/operators';

import { AlertService, UserService, AuthenticationService } from '@/_services';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
  registerForm!: FormGroup;
  loading = false;
  submitted = false;
  isChecked = false;

  constructor(
    private formBuilder: FormBuilder,
    private router: Router,
    private authenticationService: AuthenticationService,
    private userService: UserService,
    private alertService: AlertService
  ) {
    // redirect to home if already logged in
    if(this.authenticationService.currentUserValue) {
      this.router.navigate(['/']);
    }
  }

  ngOnInit() {
    this.registerForm = this.formBuilder.group({
      email: ['', [Validators.required, Validators.email]],
      username: ['', Validators.required],
      password: ['', [Validators.required, Validators.minLength(6)]],
      terms_and_conditions: ['', Validators.required]
    });
  }

  // convenience getter for easy access to form fields
  get f() { return this.registerForm.controls; }

  setTermsAndConditions() {
    this.f.terms_and_conditions.setValue(1);
  }

  onSubmit() {
    this.submitted = true;
    console.log(this.registerForm.value);
    // stop here if form is invalid
    if(this.registerForm.invalid) {
      return;
    }

    this.loading = true;
    this.userService.register(this.registerForm.value)
      .pipe(first())
      .subscribe(
        data => {
          this.alertService.success('Registration successful', true);
          this.router.navigate(['/login']);
        },
        error => {
          this.alertService.error(error);
          this.loading = false;
        });
  }
}

component.html(相关部分):

<div class="form-group">
    <input type="checkbox" formControlName="terms_and_conditions" class="form-control" 
            [ngClass]="{'is-invalid': submitted && f.terms_and_conditions.errors}" [value]="isChecked ? 1 : 0">I accept the terms and conditions
    <div *ngIf="submitted && f.terms_and_conditions.errors" class="invalid-feedback">
        <div *ngIf="f.terms_and_conditions.errors.required">You need to agree to our terms and conditions</div>
    </div>
</div>

我可以将后端api更改为接受true / false而不是1/0,但这意味着api越来越依赖于angular定义true / false的方式(例如,如果另一个框架将其定义为是非题,那么我将不得不更改api以解决此问题。所以,我不想这么做。

关于采用什么Angular方法的任何建议?

2 个答案:

答案 0 :(得分:2)

只需将此行添加到您的onSubmit()函数中,就可以解决问题。

onSubmit() {
  ...
  // THIS ONE
  this.registerForm.value.terms_and_conditions = this.registerForm.value.terms_and_conditions ? 1 : 0;
  ...
  this.userService.register(this.registerForm.value)
    .pipe(first())
    .subscribe(...);
}

答案 1 :(得分:1)

以下链接的解决方案似乎有点长,但是如果有一天需要对复选框的值进行更多的自定义。如果您需要检查则为“是”,否则为“否”。看看可能对您有帮助。

Create a ng-true-value & ng-false-value directive for Angular