简体   繁体   中英

Reading Checkbox FormControl value in Angular Reactive Form

I have the following code

if (this.myForm.value['isDefault'] === true)

Where isDefault is a checkbox FormControl. Now if the checkbox is checked I am expecting this.myForm.value['isDefault'] will result in true. When I alert this, it indeed shows true but this comparison does not result in true.

You need recheck your form and code in TS file. I reproduce it still work correctly.

HTML

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

</div>

TS

export class AppComponent {

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

  check() {
    console.log(this.theForm.value['firstCheck'] === true)
  }
}

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

If you want a value of a form control , you can also access using form.get('key').value .

I forked @Hien Nguyen's stckblitz :

Refer : https://stackblitz.com/edit/checkbox-reactive-hdwhsj?file=app/app.component.ts

So i would use : this.myForm.get('isDefault').value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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