gpt4 book ai didi

angular - 使用自动完成和 "updateOn: ' 模糊时防止提前验证'”

转载 作者:搜寻专家 更新时间:2023-10-30 21:48:10 40 4
gpt4 key购买 nike

我的 Angular 应用程序使用在服务器端执行的复杂验证。出于这个原因,我配置了仅在 blur 事件上触发更新和验证:

this.form = new FormGroup(
{ ... },
{
updateOn: 'blur'
}
);

除了使用自动完成的字段外,它工作得很好。如果自动完成功能打开并且用户用鼠标单击一个条目,则会发生一系列不幸的事件:

  • blur 事件被触发
  • 验证以不完整的旧值运行并添加错误
  • 将选定的自动完成值放入字段中
  • 自动完成弹出窗口关闭,字段再次获得焦点

结果如下所示(简化示例)。文本字段中有一个有效值,但它被标记为错误,因为验证是在旧值上运行的。

enter image description here

从技术上讲,运行验证是正确的,因为单击自动完成弹出窗口会导致 blur 事件。但是,从 UI 的 Angular 来看,这是无稽之谈。当您完成该字段并转到下一个字段时,应该会进行验证。

那么如何防止模糊事件和早期验证呢?

我创建了一个简单的 StackBlitz example .它使用类似的设置,但在客户端运行验证(并检查文本是否以“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>&nbsp;</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(); 您可以在您想要的每个事件中进行模糊处理,而不仅仅是在输入框外单击。希望这会有所帮助。

关于angular - 使用自动完成和 "updateOn: ' 模糊时防止提前验证'”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50999349/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com