表单验证在 angular 中不起作用? [英] Form validation is not working in angular?

查看:26
本文介绍了表单验证在 angular 中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查下拉列表是否为空.

需要显示所需的消息和

如果不为空,启用提交按钮.

如果为空,则禁用提交按钮.下面是我的html

下面是我的 html

<form [formGroup]="myForm" (ngSubmit)="save()" ><mat-form-field><mat-select formControlName="name" placeholder="Element List" (selectionChange)="elementSelectionChange($event)" required><mat-option *ngFor="let element of Elements" [value]="element.name">{{ 元素名称 }}</mat-option></mat-select><mat-error *ngIf="myForm.hasError('required', 'name')">请选择一个名称</mat-error></mat-form-field><mat-form-field><mat-select formControlName="symbol" placeholder="Symbol List" required><mat-option *ngFor="let element of selectedElementSymbol" [value]="element.symbol">{{ element.symbol }}</mat-option></mat-select><mat-error *ngIf="myForm.hasError('required', 'symbol')">请选择一个符号</mat-error></mat-form-field><div mat-dialog-actions><button mat-button (click)="onNoClick()">取消</button><button type="submit" mat-button cdkFocusInitial>添加</button>

</表单>

下面是我的组件

导出类 DialogOverviewExampleDialog {我的表格:表格组;symbol = new FormControl('', Validators.required);name = new FormControl('', Validators.required);构造函数(public dialogRef: MatDialogRef,@Inject(MAT_DIALOG_DATA) 公共数据:任何,私有表单构建器:FormBuilder){this.myForm = this.formBuilder.group({名称:[this.name],符号:[this.symbol],});}节省() {console.log(this.myForm.value);}}

在此处更新演示

解决方案

您当前正在为表单控件分配表单控件,而您想要为表单控件分配值.下面您将表单控件 name 分配给 formcontrol name:

错误:

name = new FormControl('', Validators.required);this.myForm = this.formBuilder.group({'name': [this.name, Validators.required],//...});

因此,只需声明名称,使用该值执行您想要的操作,然后将该值分配给您的表单控件...

正确:

名称:字符串;this.myForm = this.formBuilder.group({'name': [this.name, Validators.required],//...});

然后只需在提交按钮上添加 [disabled]="!myForm.valid".

至于另一个问题,默认情况下,除非该字段已被触摸,否则 Angular 材料不会显示错误消息,因此您需要有一个自定义错误状态匹配器,即使未触摸该字段也会显示错误(如果是你想要什么):

import {ErrorStateMatcher} from '@angular/material/core';导出类 MyErrorStateMatcher 实现 ErrorStateMatcher {isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {返回 !!(control.invalid);}}

并在您的 TS 中声明一个错误状态匹配器:

matcher = new MyErrorStateMatcher();

并在模板中使用:

这是你的

StackBlitz

I want to check whether the dropdown is empty.

Need to show the required message and

If not empty, enable the submit button.

If empty, disable the submit button. Below is my html

Below is my html

<form  [formGroup]="myForm"  (ngSubmit)="save()" >
<mat-form-field>
  <mat-select formControlName="name" placeholder="Element List"  (selectionChange)="elementSelectionChange($event)" required>
    <mat-option *ngFor="let element of Elements" [value]="element.name">
      {{ element.name }}
    </mat-option>
  </mat-select>
  <mat-error *ngIf="myForm.hasError('required', 'name')">Please choose an name</mat-error>
</mat-form-field>
<mat-form-field>
  <mat-select  formControlName="symbol"  placeholder="Symbol List" required>
    <mat-option *ngFor="let element of selectedElementSymbol" [value]="element.symbol">
      {{ element.symbol }}
    </mat-option>
  </mat-select>
  <mat-error *ngIf="myForm.hasError('required', 'symbol')">Please choose an symbol</mat-error>
</mat-form-field>

<div mat-dialog-actions>

  <button mat-button (click)="onNoClick()">Cancel</button>
<button type="submit"  mat-button cdkFocusInitial>Add</button>
</div>
</form>

below is my component

export class DialogOverviewExampleDialog {

  myForm: FormGroup;
  symbol = new FormControl('', Validators.required);
  name = new FormControl('', Validators.required);
  constructor(
    public dialogRef: MatDialogRef<DialogOverviewExampleDialog>,
    @Inject(MAT_DIALOG_DATA) public data: any,
    private formBuilder: FormBuilder) {

    this.myForm = this.formBuilder.group({
      name: [this.name],
      symbol: [this.symbol],
    });
  }

  save() {

    console.log(this.myForm.value);
  }

}

updated demo here

解决方案

You are currently assigning formcontrols to your formcontrol, whereas you want to assign value to your form controls. Below you are assigning form control name to formcontrol name:

WRONG:

name = new FormControl('', Validators.required);

this.myForm = this.formBuilder.group({
  'name': [this.name, Validators.required],
  // ...
});

so instead, just declare name, do what you want with the value, then assign that value to your form control...

CORRECT:

name: string;

this.myForm = this.formBuilder.group({
  'name': [this.name, Validators.required],
  // ...
});

Then just add [disabled]="!myForm.valid" on your submit button.

As for the other question, by default Angular material doesn't show error message unless the field has been touched, so you need to have a custom error state matcher that shows the error even when field is not touched (if that is what you want):

import {ErrorStateMatcher} from '@angular/material/core';

export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    return !!(control.invalid);
  }
}

and in your TS, declare a error state matcher:

matcher = new MyErrorStateMatcher();

and use in template:

<mat-select formControlName="name" ... [errorStateMatcher]="matcher">

Here's your

StackBlitz

这篇关于表单验证在 angular 中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆