简体   繁体   English

Angular 5反应形式设置mat-checkbox来检查

[英]Angular 5 reactive form set mat-checkbox to check

I am trying to use mat-checkbox with reactive forms on Angular 5.1.2 and Angular Material 5.0.2. 我试图在Angular 5.1.2和Angular Material 5.0.2上使用mat-checkbox和反应形式。

Everything is working well except that when I use patchValue({amateur: [false]) it is still checked. 一切都运行良好,除了当我使用patchValue({amateur:[false])时,它仍然被检查。 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. 仅以“业余”为例。

The formControl amateur.value is always false. formControl amateur.value始终为false。 However once the patched value is executed, the control is checked. 但是,一旦执行了修补值,就会检查控件。

What am I missing? 我错过了什么?

HTML5 HTML5

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

TypeScript 打字稿

FormBuilder works and display is correct. FormBuilder的工作和显示是正确的。

this.showClassGrp = this.fb.group({

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

patch showClassGrp and all the checkboxes are checked even thou the formControl value for them are false. 补丁showClassGrp和所有复选框都被检查,即使它们的formControl值为false。

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

If you're using reactive from, you may want to assign a FormControl to each member in the form. 如果您使用的是“响应”,则可能需要为表单中的每个成员分配一个FormControl。 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM