1

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.

5
  • Can you try console.log(typeof this.myForm.value['isDefault']) ? And show the output Commented Jun 27, 2019 at 15:41
  • Can you post the all of the code surrounding this logic ? For example how you update your model when someone clicks on the checkbox and so one. Otherwise it is difficult to help you with just those info. Commented Jun 27, 2019 at 15:41
  • 1
    @R3tep Its boolean Commented Jun 27, 2019 at 15:44
  • Can you show more code and HTML? A checkbox (or any form element)'s value is not always the same as it's checked state. Commented Jun 27, 2019 at 15:51
  • Its working. I did not test properly. Sorry about that. Commented Jun 27, 2019 at 15:54

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.