在表单中,我有一个自动完成字段,可以过滤和检查输入(必须是列表的元素)。它工作完美,但它是用 Angular 7 编码的。
我必须将项目迁移到Angular 15,但它不再工作了:控制正常,但过滤器不起作用。
在 Angular 材料网站上,使用了属性 [formControl],但是当我将其添加到我的字段时,过滤器正常,但控件失败......
我在网上找不到任何在 ANGULAR 15 中完成这项工作的示例
html原代码
<mat-form-field class="example-full-width" appearance="fill">
<mat-label>Rôle</mat-label>
<input #autoCompleteRoleInput type="text" matInput [matAutocomplete]="role" formControlName="role">
<mat-autocomplete #role="matAutocomplete" [displayWith]="displayFnRole">
<mat-option *ngFor="let option of filteredRoles | async" [value]="option">
{{option.libelle}}
</mat-option>
</mat-autocomplete>
<mat-error *ngIf="form.controls['role'].errors?.forbiddenRoles">
Veuillez choisir un élément de la liste.
</mat-error>
</mat-form-field>
结果: 控制正常:
过滤失败:
如果我添加 [formControl]="roleControl" 属性:过滤正常但检查失败
TS代码:
export class DialogUtilisateurComponent implements OnInit, AfterViewInit {
@ViewChild('autoCompleteRoleInput', { read: MatAutocompleteTrigger} ) autoCompleteRoleInput: MatAutocompleteTrigger;
rolesList: Role[];
roleControl = new FormControl<string | Role>('');
filteredRoles: Observable<Role[]>;
形式:
createForm(user: UserInfo) {
this.form = this.formBuilder.group({
username: [user.username, Validators.required],
name: [user.name, Validators.required],
role: [user !== null && user.roleDTO !== null ? user.roleDTO : {} as Role,
[this.inputServices.forbiddenRolesValidator(this.rolesList)]],
email: [user.email, [Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$')]],
telephone: [user.telephone, Validators.required]
});
this.form.controls['role'].setValidators(this.inputServices.forbiddenRolesValidator(this.rolesList));
this.form.controls['role'].updateValueAndValidity();
this.filteredRoles = this.roleControl.valueChanges.pipe(
startWith(''),
map(value => {
const name = typeof value === 'string' ? value : value?.libelle;
return name ? this._filter(name as string) : this.rolesList.slice();
}),
);
}
过滤器:
private _filter(value: string): Role[] {
const filterValue = value.toLowerCase();
console.log('filtre avec: ' + value);
this.rolesList.forEach((item) => {
console.log(item.libelle);
})
return this.rolesList.filter(option => option.libelle.toLowerCase().indexOf(filterValue) === 0);
}
检查:
forbiddenRolesValidator(rolesList: Role[]): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } | null => {
// below findIndex will check if control.value is equal to one of our options or not
const index = rolesList.findIndex(role => {
return control.value !== null ? role.libelle === control.value.libelle : null;
});
return index < 0 ? {'forbiddenRoles': {value: control.value}} : null;
};
}
我建议更新你的代码
角度 15 的示例 https://v15.material.angular.io/components/autocomplete/examples