angular的自定义窗体错误消息

angular的自定义窗体错误消息
插件名称 ng-error-messages
发布时间 2020年5月24日
插件作者 ouracademy

一组有助于您处理无效时在表单字段上显示错误消息的类。

安装:

# NPM
$ npm install ng-error-messages --save

使用:

1.导入ErrorMessageModule:

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { AppComponent }           from './app.component';
import { ErrorMessageModule } from 'ng-error-messages';

@NgModule({
  imports: [
    BrowserModule,
    HttpModule,
    ErrorMessageModule
  ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

2.为您的应用程序初始化DisplayErrorService:

import { Component } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { DisplayErrorService } from 'ng-error-messages'

@Component({
  selector: 'demo-app',
  templateUrl: 'index.component.html'
})
export class IndexComponent {
  form: FormGroup;
  valueFormated
  constructor(
    private displayErrorService: DisplayErrorService,
    private fb: FormBuilder) { }

  ngOnInit(): void {
    this.buildForm();
  }


  buildForm(): void {
    this.form = this.fb.group({
      'text': ['', [
        Validators.required,
        Validators.minLength(5),
        Validators.maxLength(10)
      ]]
    });
  }
  setLanguage(lang) {
    this.displayErrorService
      .setLanguage(lang)
      .subscribe(r => {
        console.log("change language")
      }, err => {
        alert(err)
      })
  }
}

3.在模板上使用它:

    <mat-card [formGroup]="form">
        <mat-card-title>
            错误信息
        </mat-card-title>
        <div>
                <input placeholder="Texto:" matInput formControlName="text">
                </input>
                <div errorMessage="text" alias="Super Texto" ></div>
        </div>
    </mat-card>