서비스에서 얻는 팀 이름 목록이 있습니다. 반응 형 폼을 사용하여 새 팀을 만드는 동안 teamName 텍스트 상자에 사용자 정의 유효성 검사기를 추가하여 해당 이름이 이미 존재하는지 확인합니다. 어느 누구도 저에게 어떻게하는지 알려주십시오. 이 경우에 유효성 검사기를 추가 할 수 있습니까?반응 형 (Model Driven Form) 제어 값이 angular2에 기존 값과 중복되는지 여부를 검증하는 방법은 무엇입니까?
1
A
답변
2
다음은 어떻게 수행 할 수있는 간단한 예입니다. 아래는 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
귀하의 검증이 양식 컨트롤의 두 번째 인수로 이동하고 검증 인수와 같은 이름의 배열을 삽입합니다. 배열에 이름 목록이 있다고 가정합니다. 다음은 사용자 정의 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
는 값이 동일한 경우 및보고 (물론 lowercasing하고 정확하게 비교하기 위해 종료 중 하나에서 공백을 제거하는대로) 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 { }
비슷한 문제가 있습니다. –
아무도 도와 드릴 수 있습니까? –