读取 Angular Reactive Form 中的复选框 FormControl 值

mua*_*f80 1 javascript typescript angular angular-reactive-forms

我有以下代码

if (this.myForm.value['isDefault'] === true)
Run Code Online (Sandbox Code Playgroud)

其中 isDefault 是复选框 FormControl。现在,如果选中该复选框,我期望 this.myForm.value['isDefault'] 结果为 true。当我警告这一点时,它确实显示为 true,但这种比较不会导致 true。

Hie*_*yen 5

您需要重新检查 TS 文件中的表单和代码。我重现它仍然可以正常工作。

超文本标记语言

<div class="container">
    <div>
        <form [formGroup]="theForm" (submit)="check()">
            Check? <input type='checkbox' formControlName="firstCheck"/>
  <input type="submit" value="check">
    </form>
    </div>

</div>
Run Code Online (Sandbox Code Playgroud)

TS

export class AppComponent {

  theForm: FormGroup;
  constructor(private fb: FormBuilder) {
    this.theForm = fb.group({
      firstCheck: false
    })
  }

  check() {
    console.log(this.theForm.value['firstCheck'] === true)
  }
}
Run Code Online (Sandbox Code Playgroud)

演示https://stackblitz.com/edit/checkbox-reactive-aagwtp?file=app%2Fapp.component.ts