将表单单选按钮设为必填字段

时间:2018-08-01 12:57:32

标签: angular radio-button radio-group

我正在Angular 6中使用表单,并且在这种情况下我禁用了提交按钮:

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

我在mat-radio-button中有2个mat-radio-group字段,如果没有选择任何单选按钮,我想禁用提交按钮。

这是我尝试过的:

<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>

因此,我已将mat-radio-button设为必需,我也尝试了将mat-radio-group设为必需,但两者均无效。

但是,如果我没有选择单选按钮,而是输入数量,则该表格将显示为有效,并且将启用提交按钮。但是,我不希望在未选择任何单选按钮时启用提交按钮,该怎么办?

谢谢

2 个答案:

答案 0 :(得分:3)

您必须将ngModelname添加到mat-radio-group中。 Als将群组设为必填项,而不是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>

为简单起见,我排除了quantity控件。 selectedRadio只是一个字符串

答案 1 :(得分:0)

您需要在使用模板驱动的表单时注册控件。控件需要在其上具有namengModel指令以将它们绑定到表单。

更正如下所示:

<mat-radio-group name="radioControl" ngModel>
    <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>