【问题标题】:Angular - Reactive Form Validation for radio groupAngular - 无线电组的反应式表单验证
【发布时间】:2021-01-08 03:13:27
【问题描述】:

如果用户在提交表单时没有选择任何选项,我想在 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;
  }
}

【问题讨论】:

    标签: angular angular-reactive-forms


    【解决方案1】:

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

    我不可能知道你的“元素”、“a”或“e.index”是什么,但如果 FormControl 有 Validators.required 如果你不选择任何东西是无效的。其他是您想在提交时显示一条消息。如果你有这样的表格,你可以使用

    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()
          
    
    }
    

    【讨论】:

      猜你喜欢
      • 2023-04-02
      • 1970-01-01
      • 2019-05-04
      • 2020-12-05
      • 1970-01-01
      • 2019-06-26
      • 2020-09-07
      相关资源
      最近更新 更多