Angular - 无线电组的反应式表单验证

Angular - Reactive Form Validation for radio group

如果用户在提交表单时没有选择任何选项,我想在 mat-radio-group 上添加验证。这是我目前所做的,但没有用。

<mat-radio-group  formControlName="{{e.Index}}">
    <mat-label>{{ et.Title }}</mat-label>
    <mat-radio-button *ngFor="let tq of e.Items" [value]="tq" [checked]="tq.IsSelected">
      {{tq.Name}}
    </mat-radio-button>
</mat-radio-group>

TS

elements.forEach((e, i) => {
  case form.id: {
    if (e.Required) {
      a = { [name]: new FormControl('', Validators.required) };
    } else {
      a = { [name]: new FormControl('') };
    }
    
    etc ...
    break;
  }
}

如果您使用 ReactiveForm 或 [(ngModel)] 不要 使用 [checked]。 Angular根据FormControl的值检查单选按钮。

我不可能知道你的“元素”、“a”或“e.index”是什么,但是如果 FormControl 有 Validators.required 如果你没有 [=26] 则无效=] 任何东西。另一个是你想在提交时显示一条消息。如果你有像

这样的形式,你可以使用
form=new FormGroup({
    control:new FormControl('',Validators.required)
  })

你可以使用类似的东西

    <form [formGroup]="form">
        <mat-radio-group aria-label="Select an option" formControlName="control">
            <mat-radio-button value="1">Option 1</mat-radio-button>
            <mat-radio-button value="2">Option 2</mat-radio-button>
            <!--I used if is "touched" to don't show the error until submit-->
            <mat-error *ngIf="form.get('control').touched">Required</mat-error>
        </mat-radio-group>
        <button (click)="submit(form)">submit</button>
    </form>

并且不要忘记在提交时将所有控件标记为已触及

submit(form)
{
     if (form.isValid)
     {
           ....
     }else
         form.markAllAsTouched()
      

}