最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Reading Checkbox FormControl value in Angular Reactive Form - Stack Overflow

programmeradmin2浏览0评论

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 parison does not result in true.

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 parison does not result in true.

Share Improve this question asked Jun 27, 2019 at 15:39 muasif80muasif80 6,0165 gold badges36 silver badges47 bronze badges 5
  • Can you try console.log(typeof this.myForm.value['isDefault']) ? And show the output – R3tep 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. – MaieonBrix Commented Jun 27, 2019 at 15:41
  • 1 @R3tep Its boolean – muasif80 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. – HBlackorby Commented Jun 27, 2019 at 15:51
  • Its working. I did not test properly. Sorry about that. – muasif80 Commented Jun 27, 2019 at 15:54
Add a ment  | 

2 Answers 2

Reset to default 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./edit/checkbox-reactive-aagwtp?file=app%2Fapp.ponent.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./edit/checkbox-reactive-hdwhsj?file=app/app.ponent.ts

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

发布评论

评论列表(0)

  1. 暂无评论