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

问题描述 投票:2回答:1

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

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

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

我错过了什么?

HTML5

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

打字稿

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.
      ...
});
angular angular-material2 angular-reactive-forms
1个回答
10
投票

如果您使用的是“响应”,则可能需要为表单中的每个成员分配一个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>
© www.soinside.com 2019 - 2024. All rights reserved.