Boh*_*s27 8 typescript angular
我在formcomponent类中有一个数组,并希望能够将该数组传递给验证器函数.在表单中添加多个验证器时,我使用的是Validators.compose函数.这只接受验证器函数的名称,而不接受任何要传递的参数.是否可以在"compose"函数内的函数调用中添加参数?
export class ClientFormComponent
{
clientForm: ControlGroup;
npi: AbstractControl;
name: AbstractControl;
constructor(private _clientService: ClientService, _fb: FormBuilder) {
this.clientForm = _fb.group({ 'name': ['', Validators.compose([Validators.required])], 'npi': ['', Validators.compose([Validators.required, npiNumValidator, Validators.maxLength(10), Validators.minLength(10)])]});
this.name = this.clientForm.controls['name'];
this.npi = this.clientForm.controls['npi'];
}
@Input() clientList;
active = true;
onSubmit(value: Client) {
this._clientService.addDeleteClient(value, true)
.subscribe(
client => this.clientList.push(client));
}
}
function npiNumValidator(control: Control): { [s: string]: boolean } {
if (isNaN(control.value)) {
return { npiNAN: true };
}
}Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助!
把它移到一个班级
class NpiNumValicator {
constructor(private someField: someType) {}
npiNumValidator(control: Control): { [s: string]: boolean } {
if (isNaN(control.value)) {
return { npiNAN: true };
}
}
}
Run Code Online (Sandbox Code Playgroud)
那就像使用它一样
this.clientForm = _fb.group({ 'name': ['',
Validators.compose([Validators.required])], 'npi': ['',
Validators.compose([Validators.required,
new NpiNumValidator(someArg).npiNumValidator,
Validators.maxLength(10), Validators.minLength(10)
])
]});
Run Code Online (Sandbox Code Playgroud)
能够this在npiNumValidator你内部使用可以使用
var npiNumVal = new NpiNumValidator(someArg);
this.clientForm = _fb.group({ 'name': ['',
Validators.compose([Validators.required])], 'npi': ['',
Validators.compose([Validators.required,
npiNumVal.npiNumValidator.bind(npiNumVal),
Validators.maxLength(10), Validators.minLength(10)
])
]});
Run Code Online (Sandbox Code Playgroud)
是否可以在"compose"函数内的函数调用中添加参数?
Validator声明: 直接出自Angular Code
/* Validator that requires controls to have a value of a minimum length. */
static minLength(minLength: number): ValidatorFn {
return (control: modelModule.AbstractControl): {[key: string]: any} => {
if (isPresent(Validators.required(control))) return null;
var v: string = control.value;
return v.length < minLength ?
{"minlength": {"requiredLength": minLength, "actualLength": v.length}} :
null;
};
}
Run Code Online (Sandbox Code Playgroud)
用法:
Validators.compose([Validators.minLength(4)]
Run Code Online (Sandbox Code Playgroud)
注意:要更好地理解它,请参阅JavaScript闭包如何工作?
| 归档时间: |
|
| 查看次数: |
12904 次 |
| 最近记录: |