angular - 使用自动完成和“updateOn:'blur'”时防止早期验证
问题描述
我的 Angular 应用程序使用在服务器端执行的复杂验证。出于这个原因,我已配置更新和验证仅在模糊事件上触发:
this.form = new FormGroup(
{ ... },
{
updateOn: 'blur'
}
);
除了使用自动完成的字段外,它工作得很好。如果自动完成功能打开并且用户用鼠标单击条目,则会发生一系列不幸的事件:
- 触发模糊事件
- 验证使用不完整的旧值运行并添加错误
- 选择的自动完成值被放入该字段
- 自动完成弹出窗口关闭,字段再次获得焦点
结果如下所示(简化示例)。文本字段中有一个有效值,但它被标记为错误,因为验证是在旧值上运行的。
从技术上讲,运行验证是正确的,因为单击自动完成弹出窗口会导致模糊事件。但是,从 UI 的角度来看,这是无稽之谈。当您完成该字段并进入下一个字段时,应该会进行验证。
那么如何防止模糊事件和早期验证呢?
我创建了一个简单的StackBlitz 示例。它使用类似的设置,但在客户端运行验证(并检查文本是否以“ABC”开头)。要重现该问题,请输入“34”,然后用鼠标从自动完成弹出窗口中选择“ABC34”。
解决方案
为了触发字符更改,我们应该触发输入事件和自动完成更改事件,所以你可以尝试这样的事情:
在组件中:
import { Component, OnInit , ViewChild , ElementRef} from '@angular/core';
import { VERSION } from '@angular/material';
import { FormGroup, FormControl } from '@angular/forms';
import { Observable, Subject } from 'rxjs';
import { startWith, map } from 'rxjs/operators';
@Component({
selector: 'material-app',
templateUrl: 'app.component.html'
})
export class AppComponent implements OnInit {
@ViewChild('textInput') textInput: ElementRef;
version = VERSION;
form: FormGroup;
abcText: string = 'ABC1';
anyText: string = '';
public readonly abcChanges: Subject<string> = new Subject<string>();
public abcSuggestions: Observable<string[]>;
ngOnInit() {
this.form = new FormGroup({
abcText: new FormControl(this.abcText),
anyText: new FormControl(this.anyText)
}, {
updateOn: 'blur'
});
this.form.valueChanges.subscribe(val => {
this.validateData(val)}
);
this.abcSuggestions = this.abcChanges.pipe(
startWith(''),
map(val => this.generateSuggestions(val))
);
}
private validateData(val: any) {
console.log(val)
// Would be more complex and happen on the server side
const text: string = val['abcText'];
const formControl = this.form.get('abcText');
if (text.startsWith('ABC')) {
formControl.setErrors(null);
} else {
formControl.setErrors({ abc: 'Must start with ABC' });
}
}
private generateSuggestions(val: string) {
let suggestions = [];
if (!val.startsWith('ABC')) {
suggestions.push('ABC' + val);
}
suggestions.push('ABC1');
suggestions.push('ABC2');
suggestions.push('ABC3');
return suggestions;
}
validateOnCharacterChange(value) {
console.log(value)
const formControl = this.form.get('abcText');
if (value.startsWith('ABC')) {
formControl.setErrors(null);
} else {
formControl.setErrors({ abc: 'Must start with ABC' });
}
// this.textInput.nativeElement.blur();
}
}
在 html 中:
<mat-toolbar color="primary">
Angular Material 2 App
</mat-toolbar>
<div class="basic-container">
<form [formGroup]="form" novalidate>
<div>
<mat-form-field>
<input matInput [matAutocomplete]="auto" formControlName="abcText" (input)="abcChanges.next($event.target.value)" placeholder="Text starting with ABC" #textInput required (input)="validateOnCharacterChange($event.target.value)">
<mat-error>Must start with 'ABC'</mat-error>
</mat-form-field>
<mat-autocomplete #auto="matAutocomplete" (optionSelected)="validateOnCharacterChange($event.option.value)">
<mat-option *ngFor="let val of abcSuggestions | async" [value]="val">{{ val }}</mat-option>
</mat-autocomplete>
</div>
<div> </div>
<div>
<mat-form-field>
<input matInput formControlName="anyText" placeholder="Any text">
<mat-error></mat-error>
</mat-form-field>
</div>
</form>
<span class="version-info">Current build: {{version.full}}</span>
</div>
检查工作中的stackblitz。
也通过使用this.textInput.nativeElement.blur();
你可以模糊你想要的每一个事件,而不仅仅是在输入之外点击。希望这可以帮助。
推荐阅读
- ruby-on-rails - 如何在 Rails 中进行异步调用并在当前视图中显示结果?
- wordpress - 在wordpress上找不到页面
- javascript - Chrome 扩展 - 脉冲/发光扩展徽标
- java - 尝试在 Java 上运行 tesseract 项目
- java - java.lang.NoSuchMethodError: org.apache.hadoop.security.UserGroupInformation.getCredentials()
- vba - Catia V5 宏:重命名功能不完整
- ruby - 使用 ruby 脚本更改文件扩展名
- php - 会话数据在 session_unset 和 session_destroy 之后仍然存在
- angular - Angular 5 HTTP 拦截器错误消息
- java - 您如何解决 intelliJ 中的“编译单元不是 SOURCE 类型”错误?