在您的组件中
@Component({
selector: 'hello',template: `
<h1>Hello {{name}}!</h1>
<form [formGroup]="primaryFormGroup">
<input type="number" formControlName="min" #min>
<input type="number" formControlName="max" #max>
<span *ngIf="this.primaryFormGroup.get('min').errors?.minIsGreaterThanMax">Min is greater than max</span>
</form>
`,styles: [`h1 { font-family: Lato; }`]
})
在您的ngOnInit
ngOnInit() {
this.primaryFormGroup.get('min').valueChanges
.subscribe(value => {
const max = this.primaryFormGroup.get('max').value
if (value > max) {
this.primaryFormGroup.get('min').setErrors({
'minIsGreaterThanMax': true
})
}
});
}
,
之所以看不到模板中的任何更改,是因为当前在代码中,直接与模板进行了一次比较。
要查看其动态更新,可以订阅表单值更改,执行比较,并在必要时设置错误。这也意味着我们需要退订onDestroy
,以防止任何内存泄漏。
import { FormBuilder,Validators } from '@angular/forms';
import {Component,ElementRef,Input,OnInit,ViewChild,OnDestroy} from '@angular/core';
import { Subscription } from 'rxjs';
import { tap } from 'rxjs/operators';
@Component({
selector: 'hello',template: `
<h1>Hello {{name}}!</h1>
<form [formGroup]="primaryFormGroup">
<input type="number" formControlName="min">
<input type="number" formControlName="max">
</form>
<span *ngIf="primaryFormGroup?.controls?.max?.errors?.minIsGreaterThanMax">Min is greater than max</span>
<!-- value changes demo -->
<pre>{{primaryFormGroup.valueChanges | async | json}}</pre>
`,styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent implements OnDestroy {
@Input() name
primaryFormGroup = this.fb.group({
min: 0,max: 0
});
private subs: Subscription[] = [];
constructor(private fb: FormBuilder) {}
ngOnDestroy() {
// cleanup
this.subs.forEach(sub => sub.unsubscribe());
}
ngOnInit() {
const checkFormForErrorsSub = this.primaryFormGroup.valueChanges.pipe(
tap(({min,max}) => {
if (min > max) {
this.primaryFormGroup.controls.max.setErrors({ minIsGreaterThanMax: true })
}
})
).subscribe();
this.subs.push(checkFormForErrorsSub);
}
}
执行验证的另一种方法是通过自定义验证器,以下资源:
官方文件:https://angular.io/guide/form-validation#custom-validators
文章:https://blog.thoughtram.io/angular/2016/03/14/custom-validators-in-angular-2.html
本文链接:https://www.f2er.com/3155349.html