13

Here is my component class where I try to set a form radio button value to 1:

import { FormGroup, FormControl } from '@angular/forms';

export class myComponent implements OnInit{
    pageForm: FormGroup;

    ngOnInit() {
        this.pageForm = new FormGroup({
            'gndr': new FormControl(1)
        });
    }
}

but when the page loaded the Radio button is not set to Male and both options are blank:

<div class="form-group">
    <label for="gender">Gender</label>
    <div class="radio">
        <label>
            <input type="radio" name="gndr" formControlName="gndr" value=1>Male
        </label>
    </div>
    <div class="radio">
        <label>
            <input type="radio" name="gndr" formControlName="gndr" value=0>Female
        </label>
    </div>
</div>

so how can I load radio button value from my component class?

1 Answer 1

22

If you want either one of them to be checked by default manually, you can add the "checked" tag e.g.

<div class="radio">
    <label>
        <input type="radio" name="gndr" formControlName="gndr" value=1 checked>Male
    </label>
</div>
<div class="radio">
    <label>
        <input type="radio" name="gndr" formControlName="gndr" value=0>Female
    </label>
</div>

Edit

If you want to use the default value as of type string, set in the FormControl:

component.ts

this.pageForm = new FormGroup({
      'gndr': new FormControl('1')
    });

component.html

...
<input type="radio" formControlName="gndr" value=1>
...

If you want to use the default value as of type number, set in the FormControl:

component.ts

this.pageForm = new FormGroup({
      'gndr': new FormControl(1)
    });

component.html

...
<input type="radio" formControlName="gndr" [value]=1>
...
Sign up to request clarification or add additional context in comments.

3 Comments

yes but how do I set it from component class based on FormControl: 'gndr': new FormControl(1)... I thought it should set the checked param. There is no sence to use FormControl and hardcode it in HTML
Ah sorry misunderstood, this should work 'gndr': new FormControl('1')
Not sure if you want the value to be of type string, like you suggest in your html view.. but that does not really make any sense to have the string type of 1 and 0. So if you like you can change the template syntax from value=1 and value=0 in your inputs to [value]=1 and [value]=0. To make sure that the values are of type number. Then it should work with your original ` 'gndr': new FormControl(1)`

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.