Angular2 how to get input type value in reactive forms

sensei picture sensei · Nov 13, 2017 · Viewed 34.1k times · Source

I am building reactive forms form in angular. I have simple radio button with gender name:

this._form = this._formBuilder.group({
            gender: ['', Validators.required]
        });

Template:

            <div class="form-group">
                <h4>What is your gender?</h4>
                <div class="form-group">
                    <label class="custom-control custom-radio">
                        <input value="male" name="gender" type="radio" class="custom-control-input" formControlName="gender">
                        <span class="custom-control-indicator"></span>
                        <span class="custom-control-description">Male</span>
                    </label>
                    <label class="custom-control custom-radio">
                        <input value="female" name="gender" type="radio" class="custom-control-input" formControlName="gender">
                        <span class="custom-control-indicator"></span>
                        <span class="custom-control-description">Female</span>
                    </label>
                    <app-field-error-display [displayError]="formValidationService.IsFieldInvalid(_form,'gender','required')" errorMsg="Field is required"></app-field-error-display>
                </div>
            </div>

I can access the control field by name like this:

public GetControl(form: FormGroup, field: string){
        return form.get(field);
    }

Based on this how do I access the attribute value of type="radio"? I want to know if input control is of type radio.

Answer

Argus Malware picture Argus Malware · Nov 13, 2017

you can access the value by using this code in your component

let genderValue = this._form.value.gender;