Angular 5 reactive form set mat-checkbox to check

Angular 5 reactive form set mat-checkbox to check

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

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

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

我错过了什么?

HTML5

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

TypeScript

FormBuilder 工作并且显示正确。

this.showClassGrp = this.fb.group({

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

补丁 showClassGrp 和所有复选框都被选中,即使它们的 formControl 值为 false。

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

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

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

<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>