我已经创建了自定义验证器(cannotContainSpace)并且想要使用它模板组件(postmessage.component),但不知何故验证器无法看到我创建的自定义验证器类..这里是编译器消息:
usernamevalidator.ts
import {FormControl} from '@angular/forms';
export class UsernameValidator{
static cannotContainSpace(control:FormControl){
if(control.value.indexOf('')>=0)
return { cannotContainSpace:true };
return null;
}
}
postmessage.component.ts
import { Component } from '@angular/core';
import {FormControl,FormGroup,FormBuilder,Validators} from '@angular/forms';
import {UsernameValidator} from '../../validators/usernamevalidator';
@Component({
moduleId:module.id,
selector: 'post-message',
templateUrl: '../../templates/postmessage.component.html'
})
export class PostComponent {
form : FormGroup;
constructor(fb:FormBuilder){
this.form = fb.group({
username:['', Validators.compose([Validators.required, Validators.cannotContainSpace])],
email:['', Validators.required],
message:['', Validators.required]
});
}
signup(){
console.log(this.form.value);
}
}
答案 0 :(得分:5)
username:['', Validators.compose([Validators.required, Validators.cannotContainSpace])],
应该是
username:['', Validators.compose([Validators.required, UsernameValidator.cannotContainSpace])],
Validators
类仅提供Validators
类中定义的验证器。