Angular 使用自动完成和“更新:模糊”时防止早期验证

Angular 使用自动完成和“更新:模糊”时防止早期验证,angular,typescript,angular-material,angular6,angular-forms,Angular,Typescript,Angular Material,Angular6,Angular Forms,我的Angular应用程序使用在服务器端执行的复杂验证。因此,我已配置更新和验证仅在模糊事件上触发: 除了使用自动补全的字段外,它工作得很好。如果“自动完成”处于打开状态,并且用户用鼠标单击某个条目,则会发生一系列不幸的事件: 将触发模糊事件 验证使用不完整的旧值运行,并添加错误 所选的自动完成值被放入字段中 自动完成弹出窗口关闭,字段再次获得焦点 结果如下面的简化示例所示。文本字段中有一个有效值,但它被标记为错误,因为验证是在旧值上运行的 从技术上讲,运行验证是正确的,因为单击自动完成弹出窗口

我的Angular应用程序使用在服务器端执行的复杂验证。因此,我已配置更新和验证仅在模糊事件上触发:

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

将触发模糊事件 验证使用不完整的旧值运行,并添加错误 所选的自动完成值被放入字段中 自动完成弹出窗口关闭,字段再次获得焦点 结果如下面的简化示例所示。文本字段中有一个有效值,但它被标记为错误,因为验证是在旧值上运行的

从技术上讲,运行验证是正确的,因为单击自动完成弹出窗口会导致模糊事件。然而,从用户界面的角度来看,这是胡说八道。验证应该在您完成该字段并转到下一个字段时进行

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


我创建了一个简单的。它使用类似的设置,但在客户端运行验证,并检查文本是否以“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>
检查工作状态

也可以使用this.textInput.nativeElement.blur;您可以在任何事件中进行模糊处理,而不仅仅是在输入之外单击。
希望这有帮助。

谢谢你的回答。但是每个字符的验证都太昂贵了。在真正的应用程序中,验证发生在服务器端,因此需要一些时间。这就是为什么我首先切换到updateOn:“blur”。我不是在寻找更频繁的验证,而是更少的验证。所以我认为选中选项就足够了,删除输入事件,这将是你想要的,我认为它不会太贵?!是的,那可能是一个解决办法。有点不幸的是,它在一个部分内被检查了两次,并且很快就会闪烁红色;但它似乎起作用了。@Codo或您可以在选择的选项上模糊,并将自动检查验证。我不确定我是否理解该解决方案。这将如何工作并改进上述解决方案?
<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>