这里有一个简单的例子来说明如何做到这一点。下面是app.component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl } from '@angular/forms';
import { CustomValidator } from './custom-validators';
const prevNames = ['hector', 'steve', 'adam', 'peter'];
@Component({
selector: 'app-root',
template: `
<div [formGroup]="newName">
<input formControlName="newName">
</div>`,
styleUrls: [`./app.component.css`]
})
export class AppComponent implements OnInit {
newName: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.newName = this.fb.group({
newName: this.fb.control('',CustomValidator.checkNamesMatched(prevNames))
});
} // End Of Init
} // End of Class
您的验证器作为表单控件中的第二个参数进入,并将您的名称数组作为验证器参数插入。
假设您有一个数组中的名称列表。下面是custom-validators.ts
export class CustomValidator {
static checkNamesMatched(arrayOfNames: string[]) {
return (control) => {
let matched = false;
arrayOfNames.forEach((value) => {
if (value.toLowerCase().trim() === control.value.toLowerCase().trim()) {
return matched = true;
}
});
return (!matched) ? null : { checkNamesMatched: true };
};
} // End of method
} // End of Class
您的验证器将遍历 arrayOfNames 的每个元素(以及从两端小写和删除空格以进行准确比较)并查看它是否等于控件中的值。如果没有匹配,它将返回 null(意味着没有错误),否则报告一个匹配(这将返回错误)。确保在组件和模块中执行所有必要的导入。希望能帮助到你!下面是 app.module 以防万一。
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }