Angular 5反应形式设置垫复选框 [英] Angular 5 reactive form set mat-checkbox to check

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

问题描述

我正在尝试在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>

TypeScript

TypeScript

FormBuilder正常工作并且显示正确.

FormBuilder works and display is correct.

this.showClassGrp = this.fb.group({

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

修补showClassGrp并检查所有复选框,即使它们的formControl值为false.

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.
      ...
});

推荐答案

如果您使用的是React 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反应形式设置垫复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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