我想检查一个文本字段的值是否大于另一个文本字段的值。如果是的话,应该设置一个错误。
这就是我尝试过的:
if (this.min.nativeElement.value > this.max.nativeElement.value) {
this.primaryFormGroup.controls.max.setErrors({
minIsGreaterThanMax: true
})
}这就是我如何尝试检查是否设置了错误:
<span *ngIf="this.primaryFormGroup.min.hasError('minIsGreaterThanMax')">Min is greater than max</span>我一定做错了什么,因为我的错误信息从未出现。
发布于 2019-11-06 02:38:19
在您的组件中
@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
})
}
});
}发布于 2019-11-06 02:51:29
您看不到模板中反映的任何更改的原因是,目前在代码中,比较是直接针对模板进行的。
要查看它的动态更新,您可以订阅表单值更改,执行比较,并在必要时设置错误。这也意味着我们需要在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://stackoverflow.com/questions/58722145
复制相似问题