首页 文章

使用自动完成和“updateOn:'blur'”时防止早期验证

提问于
浏览
1

我的Angular应用程序使用在服务器端执行的复杂验证 . 出于这个原因,我已经配置只在模糊事件上触发更新和验证:

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

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

  • 触发模糊事件

  • 验证使用不完整的旧值运行并添加错误

  • 将选定的自动填充值放入字段中

  • 自动完成弹出窗口已关闭,字段再次获得焦点

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

enter image description here

从技术上讲,运行验证是正确的,因为单击自动完成弹出窗口会导致模糊事件 . 但是,从UI的角度来看,它已经完成了字段并继续前进到下一个字段 .

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

我创建了一个简单的StackBlitz example . 它使用类似的设置,但在客户端运行验证(并检查文本以'ABC'开头) . 要重现该问题,请输入"34",然后使用鼠标从自动完成弹出窗口中选择"ABC34" .

1 回答

  • 1

    为了触发字符更改,我们应该触发输入事件也是自动完成更改事件,所以你可以尝试这样的事情:

    在组件中:

    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(); ,您可以在所需的每个事件中模糊,而不仅仅是在输入外部点击 . 希望这可以帮助 .

相关问题