我正在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设为必需,但两者均无效。
但是,如果我没有选择单选按钮,而是输入数量,则该表格将显示为有效,并且将启用提交按钮。但是,我不希望在未选择任何单选按钮时启用提交按钮,该怎么办?
谢谢
答案 0 :(得分:3)
您必须将ngModel
和name
添加到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)
您需要在使用模板驱动的表单时注册控件。控件需要在其上具有name
和ngModel
指令以将它们绑定到表单。
更正如下所示:
<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>