Angular 如何根据用户输入设置角度复选框的二进制值?
我是Angular的新手,我正在尝试建立一个简单的注册页面。我需要发送emailid、用户名、密码,以及基于用户是否接受条款和条件的1/0值 我使用复选框来检测用户是否接受了条款和条件 问题是Angular正在向api发送真/假值,而api期望值为1/0 我尝试过使用isChecked变量设置该值。该值在html中设置正确,但在提交表单时,它仍然发送真/假值 组件1.ts:Angular 如何根据用户输入设置角度复选框的二进制值?,angular,Angular,我是Angular的新手,我正在尝试建立一个简单的注册页面。我需要发送emailid、用户名、密码,以及基于用户是否接受条款和条件的1/0值 我使用复选框来检测用户是否接受了条款和条件 问题是Angular正在向api发送真/假值,而api期望值为1/0 我尝试过使用isChecked变量设置该值。该值在html中设置正确,但在提交表单时,它仍然发送真/假值 组件1.ts: import { Component, OnInit } from '@angular/core'; import { R
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(相关部分):
我接受条款和条件
你需要同意我们的条款和条件
我可以将后端api更改为接受true/false而不是1/0,但这意味着api将变得依赖于angular定义true/false的方式(例如,如果另一个框架将其定义为true/false,那么我必须更改api来处理该问题)。所以,我不想那样做
有什么建议吗?只需将这一行添加到
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(...);
}
下面链接的解决方案似乎有点长,但如果有一天您需要对复选框值进行更多的自定义,请参阅。比如,如果你需要一个“是”如果勾选,如果不勾选则为“否”。看一看可能对你有帮助
谢谢。我去看看。
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(...);
}