1

I am completely new to Angular and I am trying to build a simple registration page following this link. I need to send the emailid, username, password, and a 1/0 value based on whether the user has accepted the terms and conditions.

I am using a checkbox to detect whether the user has accepted the terms and conditions.

The problem is that Angular is sending a true/false value to the api and the api expects a 1/0 value.

I have tried setting the value using a isChecked variable. The value gets set alright in the html but while submitting the form, it is still sending true/false value.

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 (relevant portion):

<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>

I can just change the backend api to accept a true/false instead of 1/0, but that would mean that the api is becoming dependent on the way angular defines true/false (For example, if another framework defines it as True/False, then I would have to change the api to take care of that). So, I don't want to do that.

Any suggestions on what's the Angular way to do this?

2 Answers 2

2

Just add this line to your onSubmit() function and that should do the trick.

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(...);
}
Sign up to request clarification or add additional context in comments.

Comments

1

The below linked solution seems to be a little long, but in case if you someday need a little more customization to your checkbox value. Like if you need a YES if checked and NO if not. Have a look might help you.

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

1 Comment

Thanks. I'll check it out.

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.