11
votes

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.

3
Maybe just check by field name ? :D so, if field == 'gender' then it's a radio. Pretty easy, or you want something more generic ?Mehdi Benmoha
generic yes, since i might have 10+ radio buttons.sensei

3 Answers

-1
votes

EDIT: This can't be solved with Reactive forms, but you can with Dynamic forms: https://angular.io/guide/dynamic-form

The following is a dirty workarround (not recommended):

Using native JS with not a good practice in Angular, because you lose a lot of Angular features, but if you're just looking for a quick and dirty fix here it is:

public GetControl(form: FormGroup, field: string){
    let el = document.querySelector('input[name="'+field+'"]');
    if(el.getAttribute('type') == 'radio'){
        // This is a radio input
    }
    return form.get(field);
}
13
votes

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

let genderValue = this._form.value.gender;
3
votes

A simple one, also provides intellisense too

Typescript

// declare a form with properties i.e. name
this.form = this.formBuilder.group({
    name: ['', Validators.required]
});

// create getter for form-property i.e.
get Name(): AbstractControl {
     return this.form.get('name')
}

HTML

<input type="text" [formControl]="Name">

{{Name.value}} // your can see your input name here