Make mat-radio-button a required field in a form
Asked Answered
A

1

13

I am using a form in Angular 6, and I am disabling the submit button on this condition:

<button tabindex="-1" mat-raised-button class="submit-btn" color="primary" type="submit" [disabled]="!EditItemForm.form.valid || !quantityIsValid(newQuantity.value)">Save</button>

I have 2 mat-radio-button fields inside a mat-radio-group, and I want to disable the submit button if none of the radio buttons are selected.

Here is what I tried:

<form #EditItemForm="ngForm" (ngSubmit)="save(newQuantity.value)">
    <mat-radio-group>
        <mat-radio-button (click)="setType('Consumable')" value="1" #consumable name="consumable" required>Consumable</mat-radio-button>
        <mat-radio-button (click)="setType('Returnable')" value="2" #returnable name="returnable" required>Returnable</mat-radio-button>
    </mat-radio-group>

    <mat-form-field>
        <input matInput [ngModel]="data.quantity" name="newQuantity" #newQuantity placeholder="Quantity"
            type="number" required>
    </mat-form-field>

    <mat-dialog-actions>
        <button tabindex="-1" mat-raised-button [mat-dialog-close]="false">Cancel</button>
        <button tabindex="-1" mat-raised-button class="submit-btn" color="primary" type="submit" [disabled]="!EditItemForm.form.valid || !quantityIsValid(newQuantity.value)">Save</button>
    </mat-dialog-actions>
</form>

So I've made the mat-radio-buttons required, I've also tried making the mat-radio-group required but both don't work.

However, if I don't select a radio button, and I type in a quantity, the form will appear to be valid and it will enable the submit button. But, I don't want the submit button to be enabled when there's no radio button selected so how can I do this?

Thanks

Alfred answered 1/8, 2018 at 12:57 Comment(0)
M
6

You have to add a ngModel & name to your mat-radio-group. Als make the group required instead of the mat-radio-buttons:

<form #EditItemForm="ngForm" (ngSubmit)="save(1)">
    <mat-radio-group required [ngModel]="selectedRadio" name="radio">
        <mat-radio-button (click)="setType('Consumable')" value="1">Consumable</mat-radio-button>
        <mat-radio-button (click)="setType('Returnable')" value="2">Returnable</mat-radio-button>
    </mat-radio-group>

   <button tabindex="-1" mat-raised-button class="submit-btn" color="primary" type="submit" [disabled]="!EditItemForm.valid">Save</button>
</form>

<p>Form valid: {{ EditItemForm.valid }}</p>

I excluded the quantity control for simplicity. The selectedRadio is just a string

Manganate answered 1/8, 2018 at 13:34 Comment(1)
Why on earth would I need to add an ngModel attribute if I'm using reactive forms? Surely there must be another way?Crocodile

© 2022 - 2024 — McMap. All rights reserved.