【问题标题】:Angular checkbox values角度复选框值
【发布时间】:2023-03-22 16:21:01
【问题描述】:

我无法在表单中设置 checkbox 值。我无法解决的问题是,当我想更新表单并获取所有数据时,checkboxes 每次都返回 true 并显示为已选中,即使 checkboxes 为 false(未选中)。

这是我的组件:

import { Component, OnInit, Inject } from '@angular/core';
import { Router } from "@angular/router";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { HttpClientService, Employee } from '../service/http-client.service';

@Component({
  selector: 'app-edit-employee',
  templateUrl: './edit-employee.component.html',
  styleUrls: ['./edit-employee.component.css']
})
export class EditEmployeeComponent implements OnInit {

  user: Employee;
  editForm: FormGroup;

  constructor(
    private formBuilder: FormBuilder,
    private router: Router,
    private httpClientService: HttpClientService) { }

  ngOnInit() {
    let userId = window.localStorage.getItem("editEmployeeId");
    if (!userId) {
      alert("Invalid action.")
      this.router.navigate(['employee']);
      return;
    }
    this.editForm = this.formBuilder.group({
      enabled: [''],
      admin: [''],
      supervisor: ['']
    });

    this.editForm.setErrors({ required: true });
    this.editForm.valueChanges.subscribe((newValue) => {
      let enabledCheckbox = (newValue.enabled) ? 'Y' : 'N';
      let adminCheckbox = (newValue.admin) ? 'Y' : 'N';
      let supervisorCheckbox = (newValue.supervisor) ? 'Y' : 'N';

      newValue.enabled = enabledCheckbox;
      newValue.admin = adminCheckbox;
      newValue.supervisor = supervisorCheckbox;

      if (newValue.admin === true || newValue.supervisor === true) {
        this.editForm.setErrors(null);
      } else {
        this.editForm.setErrors({ required: true });
      }

    });
    this.httpClientService.getEmployeeById(+userId)
      .subscribe(data => {
        this.editForm.patchValue(data);
      });
  }

  onSubmit() {

    this.httpClientService.updateEmployee(this.editForm.value)
      .subscribe(
        data => {
            this.router.navigate(['employee']);
        },
        error => {
          // alert(error);
        });
  }

}

还有我的html:

<div class="col-md-6">
  <h2 class="text-center">Edit user</h2>
  <form [formGroup]="editForm" (ngSubmit)="onSubmit()">

    <div class="form-group">
      <mat-checkbox formControlName="enabled" class="form-control" color="primary">
        Enabled</mat-checkbox>
    </div>

    <div class="form-group">
      <mat-checkbox formControlName="admin" class="form-control" color="primary">
        Admin</mat-checkbox>
    </div>

    <div class="form-group">
      <mat-checkbox formControlName="supervisor" class="form-control" color="primary">
        Supervisor</mat-checkbox>
    </div>

    <div class="form-group">
      <button mat-raised-button color="primary" type="button" class="btn btn-success" (click)="onSubmit()"
        routerLink="/">Update</button>
    </div>
  </form>
</div>

在我将它们设置为更新后,一切正常并获得checkboxes 的正确状态并保存在表中,但如果我想更新,那么它们总是显示为在表单中选中,有什么建议为什么会发生这种情况?

【问题讨论】:

  • 您的所有值都是必需的吗?为什么不使用Validators.required?
  • 您是否尝试过将复选框控件初始化为布尔值? ``` this.editForm = this.formBuilder.group({ enabled: [false], admin: [false], supervisor: [false] }); ```
  • 是的,这不会帮助它在 newValue 部分覆盖它并自动将其设置为 true

标签: angular checkbox angular-material


【解决方案1】:

我认为这是因为在每次更改时,您都将复选框的值设置为一个非空字符串,该字符串强制转换为 true。您还需要确保您发出的请求的数据结构符合表单:

interface Employee {
    ...
    enabled: boolean;
    admin: boolean;
    supervisor: boolean;
    ...
}

在更改订阅中,您根本不需要设置值,复选框会自动切换并将值存储在 FormGroup 中。

【讨论】:

    【解决方案2】:

    所以经过几次尝试,我终于设法让checkbox 显示他们必须显示的当前状态。

    我是这样做的:

        this.httpClientService.getEmployeeById(+userId)
          .subscribe(data => {
            this.user = data;
            this.user.enabled = this.formatCheckboxesToTrueOrFalse(this.user.enabled);
            this.user.admin = this.formatCheckboxesToTrueOrFalse(this.user.admin);
            this.user.supervisor = this.formatCheckboxesToTrueOrFalse(this.user.supervisor);
            this.editForm.patchValue(data);
            console.log(data);
          });
      }
    
      formatCheckboxesToTrueOrFalse(checkbox) {
        let formattedCheckboxes = null
        switch (checkbox) {
          case 'Y': formattedCheckboxes = true;
    
            break;
          case 'N': formattedCheckboxes = false;
    
            break;
          default:
            break;
        }
        return formattedCheckboxes;
      }
    

    当它们从数据库中获取值时,我必须对其进行格式化(“Y”表示选中,“N”表示未选中)并订阅该格式化数据,现在它可以工作了!

    【讨论】:

      猜你喜欢
      • 2020-03-02
      • 2015-04-02
      • 1970-01-01
      • 1970-01-01
      • 2020-10-31
      • 2022-11-28
      • 2020-03-03
      • 1970-01-01
      • 2021-02-22
      相关资源
      最近更新 更多