角度材质 - 按钮单击时显示mat-error

时间:2017-10-14 13:35:14

标签: angular typescript angular-material

我正在尝试使用<mat-for-field><mat-error>进行验证。当用户选中输入而不填充时,这可以正常工作。但是,如何在单击按钮时强制显示此错误?我没有使用提交。此外,使用模板驱动的表单。

这是我的代码:

HTML:

<mat-form-field>
    <input matInput placeholder="Due Date" name="dueDate" [(ngModel)]="dueDate" [formControl]="dueDateValidator" required>
    <mat-error *ngIf="dueDateValidator.invalid">Due Date is required for Tasks</mat-error>
</mat-form-field>

TS:

dueDateValidator: FormControl = new FormControl('', [Validators.required]);

10 个答案:

答案 0 :(得分:18)

了解如何使用自定义ErrorStateMatcher

的表单
  

如果您希望覆盖此行为(例如,要尽快显示错误)   因为无效控件是脏的或父表单组是   无效),您可以使用matInput的errorStateMatcher属性。   该属性采用ErrorStateMatcher对象的实例。一个   ErrorStateMatcher必须实现单个方法isErrorState   获取此matInput的FormControl以及父窗体和   返回一个布尔值,指示是否应显示错误。 (真正   表明它们应该被显示,并且表示它们是错误的   不应该。)

我会创建一个单独的文件,例如default.error-matcher.ts

/** Error when invalid control is dirty or touched*/
export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    return !!(control && control.invalid && (control.dirty || control.touched));
  }
}

然后在TS文件中添加:

matcher = new MyErrorStateMatcher();

然后更改输入以使用匹配器:

<mat-form-field>
    <input matInput placeholder="Due Date" name="dueDate" [(ngModel)]="dueDate" [formControl]="dueDateValidator" [errorStateMatcher]="matcher" required>
    <mat-error *ngIf="dueDateValidator.invalid">Due Date is required for Tasks</mat-error>
</mat-form-field>

答案 1 :(得分:9)

由于要在单击按钮时显示错误,请尝试以下操作: 对于Angular6版本:

1). import below:
    import { FormControl, FormBuilder, FormGroup } from '@angular/forms';

2). declare form control in .ts file:
    nameControl = new FormControl('');

3). put control in html:
    <mat-form-field  style="width: 100%" floatPlaceholder="never">
      <input matInput placeholder="your placeholder text" [formControl]="nameControl" 
        required/>
      <mat-error *ngIf="nameControl.errors?.required">name is required</mat-error>
    </mat-form-field>

3). on button's click:
    this.nameControl.markAsTouched();

检查表单控件的使用方式非常重要,第3点上的“ .markAsTouched()”将显示相应表单控件的错误。

答案 2 :(得分:2)

基于Kyle Pfromer的帖子,我发现了我的解决方案(同样的问题):

在TS文件中,我在找到无效表单后添加了StateMatcher,例如

if (this.myFormGroup.invalid) {
  this.matcher = new MyErrorStateMatcher();
  return;
}

在MyErrorStateMatcher类中,我更改如下:

    return !!(control && control.invalid);

我发现Angular Material无法检测到错误令人困惑。

答案 3 :(得分:2)

这对我有用。 :)在按钮上单击:

CREATE TABLE my_ks.my_table (
  id uuid primary key,
  mt frozen<my_type>
);

答案 4 :(得分:2)

您可以按照“凯尔·普弗默(Kyle Pfromer)”的建议进行操作,或者在使用表单组时,可以使用以下方式将元素标记为在提交时被触摸

onSubmit(){ this.formName.get('formControlName').markAsTouched(); }

答案 5 :(得分:1)

Angular 8具有新的表单方法:markAllAsTouched();

这会将控件/表单和所有后裔标记为已触摸!!!

所以:

this.form.markAllAsTouched();

是解决方案。

答案 6 :(得分:0)

您也可以点击按钮轻松调用AbstractControl.updateValueAndValidity()功能。这将再次对相应的ForControl运行验证过程并显示错误(如果有的话)(基于您的验证器)。

所以,在你的例子中:

    checkForErrorsOnButtonClick(): void {
      dueDateValidator.updateValueAndValidity();
    }

答案 7 :(得分:0)

我为不同的情况提供3种不同的解决方案,请使用适合您的解决方案。

  • 如果您使用的是表格,则

    this.form.markAllAsTouched();
    
  • 如果需要在表单中影响特定字段,请过滤该nameControl并执行

    nameControl.markAsTouched();
    
  • 如果您不使用表单,请为ref元素指定input并在ts文件中初始化变量,并执行以下操作,

    @ViewChild('myInputRef') myInputRef; // Initialize the ref of input element
    .
    .
    this.myInputRef.control.markAsTouched()
    

答案 8 :(得分:0)

最简单的方法是在模板上单击按钮时调用markUserNameTouched()方法,如下所示。我们在formControl上使用markAsTouched()。

public staffLoginForm: FormGroup;
ngOnInit(){
this.staffLoginForm = new FormGroup({
username: new FormControl(null),
password: new FormControl(null)});

markUserNameTouched():void{
  this.staffLoginForm.get('username').markAsTouched();
}

答案 9 :(得分:0)

全局:在键入或触摸时显示 mat-error: 与提供的解决方案不同,此方法将处理应用中的所有 mat-error,而无需将匹配器应用于每个输入。

1- 创建 touched-error-state.matcher.ts 文件:

import {FormControl, FormGroupDirective, NgForm } from '@angular/forms';
import {ErrorStateMatcher} from '@angular/material/core';

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

2- 在 app.module 导入:

import { ErrorStateMatcher } from '@angular/material/core';
import { TouchedErrorStateMatcher } from './your-folder-path/touched-error-state.matcher';

3- 现在将其提供给提供者:

@NgModule({
  providers: [
    AuthService,
    UserService,
    { provide: ErrorStateMatcher, useClass: TouchedErrorStateMatcher }
  ],
})

4- 重新提供应用程序。

相关问题