添加自定义验证时,出现如下错误: 错误TypeError:无法读取html文件中未定义的属性“ get”,因为我使用了以下验证错误:
我的代码如下:
form: FormGroup;
ngOnInit() {
this.form = this.fb.group({
test1: [ '', [ Validators.required ] ],
test2: [''],
test3: [''],
}, {
validator: this.testValidation('test1', 'test2')
});
}
function testValidation(test1: string, test2: string) {
return (group: FormGroup): {[key: string]: any} => {
let test1 = group.controls[test1];
let test2 = group.controls[test2];
if (test1.value !== test2.value) {
return {
failTest: true
};
}
<form [formGroup]="form" (ngSubmit)="submit()">
<input type="text" class="form-control" formControlName="test1" >
<div *ngIf="form.get('test1').hasError('required')>Error1</div>
<input type="text" class="form-control" formControlName="test2" >
<div *ngIf="form.get('test2').hasError('failTest')>Error2</div>
</form>
为什么我在行中出错:
<div *ngIf="form.get('test1').hasError('required')>Error1</div>
答案 0 :(得分:0)
答案 1 :(得分:0)
尝试:
组件ts:
export class AppComponent implements OnInit {
form: FormGroup; //define here
constructor(private fb:FormBuilder){ //initialize in constructor
this.form = this.fb.group({
test1: [ '', [ Validators.required ] ],
test2: [''],
test3: [''],
}, {
validator: this.testValidation('test1', 'test2')
});
}
ngOnInit(){}
testValidation(test1: string, test2: string) {
return (group: FormGroup): {[key: string]: any} => {
let test1 = group.controls['test1'];
let test2 = group.controls['test2'];
if (test1.value !== test2.value) {
return {
failTest: true
};
}
}
}
}
html:
<form [formGroup]="form" (ngSubmit)="submit()">
<input type="text" class="form-control" formControlName="test1" >
<div *ngIf="form.get('test1').hasError('required')">Error1</div>
<input type="text" class="form-control" formControlName="test2" >
<div *ngIf="form.get('test2').hasError('failTest')">Error2</div>
</form>
工作DEMO