Angular 5 反应形式设置 mat-checkbox 来检查 [英] Angular 5 reactive form set mat-checkbox to check

查看:18
本文介绍了Angular 5 反应形式设置 mat-checkbox 来检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Angular 5.1.2 和 Angular Material 5.0.2 上使用带有反应形式的 mat-checkbox.

I am trying to use mat-checkbox with reactive forms on Angular 5.1.2 and Angular Material 5.0.2.

一切正常,除了当我使用 patchValue({amateur: [false]) 时,它仍然被检查.奇怪的是我有其他形式,我在做同样的事情并且它们工作正常.它也不仅仅是业余复选框,它是所有复选框都被选中.仅以业余"为例.

Everything is working well except that when I use patchValue({amateur: [false]) it is still checked. What is weird is I have other forms where I am doing the same thing and they work fine. It also isn't just the amateur checkbox, it is all the checkboxes are checked. Just using "amateur" as an example.

formControl amateur.value 始终为 false.但是,一旦执行了修补值,就会检查控制.

The formControl amateur.value is always false. However once the patched value is executed, the control is checked.

我错过了什么?

HTML5

 <form [formGroup]="showClassGrp">
   <mat-checkbox id="amateur" class="amateur" color="primary" 
      formControlName="amateur">Amateur</mat-checkbox>
 </form>

打字稿

FormBuilder 工作正常且显示正确.

FormBuilder works and display is correct.

this.showClassGrp = this.fb.group({

  ...
  amateur: [false],
  ...
});

补丁 showClassGrp 和所有复选框都被选中,即使它们的 formControl 值是假的.

patch showClassGrp and all the checkboxes are checked even thou the formControl value for them are false.

    this.showClassGrp.patchValue({
      className: [this.showClass.className],  //this works
      amateur: [false],  // this changed the display to checked.
      ...
});

推荐答案

如果您使用的是反应式 from,您可能需要为表单中的每个成员分配一个 FormControl.像这样

If you're using reactive from, you may want to assign a FormControl to each member in the form. Something like this

component.ts

component.ts

  showClassGrp: FormGroup;

  constructor() { }

  ngOnInit() {


    this.showClassGrp = new FormGroup({
      'amateur': new FormControl(false),
    });

  }

  onSubmit(){
    console.log(this.showClassGrp.value.amateur);
    this.showClassGrp.patchValue({amateur: false});
    console.log(this.showClassGrp.value.amateur);
  }

component.html

component.html

<form [formGroup]="showClassGrp" (ngSubmit)="onSubmit()">
  <mat-checkbox id="amateur" class="amateur" color="primary"
                formControlName="amateur">Amateur</mat-checkbox>
  <button class="btn btn-primary" type="submit"> Submit </button>
</form>

这篇关于Angular 5 反应形式设置 mat-checkbox 来检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆