为了在字符更改时触发,我们应该触发输入事件并自动完成更改事件,因此您可以尝试以下操作:
组件中:
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();
你可以在任何需要的事件中模糊,而不仅仅是在输入之外单击。
希望这有帮助。