FormBuilder始终为复选框返回null

时间:2019-07-18 11:02:58

标签: javascript html angular

我正在创建一个基本的登录页面。如果输入密码,则所有用户要做的事情,然后如果要添加其他用户,请勾选该框。他们只有在拥有正确权限的情况下,才能添加其他用户(这一点我将能够弄清楚自己)。

我设法使密码输入起作用,用户在此输入密码,然后我可以将其登录到控制台(请记住,这只是一个测试)。我似乎无法读取该复选框的值,它总是返回null

HTML

<div class="login">
  <h2 class="login-header">Log in</h2>
  <form [formGroup]="loginForm" class="login-container" (ngSubmit)="login()">


    <p [ngClass]="{ 'has-error': isSubmitted && formControls.password.errors }">
      <input type="password" placeholder="Password" formControlName="password" autofocus  autocomplete="off">
    </p>

    <p>
      <input id="addUser" type="checkbox" name="addUser" value="addUser" formcontrolName="checkbox">Add User?
    </p>

    <div id="invalid">
      <p>Invalid Login... Try Again</p>
    </div>
    <p>
      <input type="submit" value="Log in">
    </p>
  </form>
</div>

.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';


@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

  constructor(private authService: AuthService, private router: Router, private FormBuilder: FormBuilder, private httpService: HttpClient) { }

  loginForm: FormGroup;
  isSubmitted = false;
  loginDetails: any = []
  loginLength: any = [];

  ngOnInit() {
    this.loginForm = this.FormBuilder.group({
      password: ['', Validators.required],
      checkbox: new FormControl
    })
  }
  get formControls() { return this.loginForm.controls}

  login() {
    var checkboxresult = this.loginForm.get('checkbox').value;
    console.log(checkboxresult)
    console.log(this.loginForm)
  }
}

选中此复选框后,我希望它返回true,而当我没有复选框时,我希望它返回false。目前,它仅返回null

我尝试遵循此guide,但返回null。按下提交后如何从表单中获取truefalse

0 个答案:

没有答案