angular - 验证 mat-autocomplete 是对象
问题描述
我是 Angular 的新手。我有一个 html 表单:
<form class="input-form" [formGroup]='terminalsForm'>
<mat-form-field class="form-full-width">
<input matInput placeholder="From" [matAutocomplete]="auto" formControlName='terminalInput' required>
</mat-form-field>
<span>Your choice is: {{terminalsForm.get('terminalInput').value | json}}</span>
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
<mat-option *ngFor="let terminal of (filteredTerminals)?.results" [value]="terminal">
<span>{{ terminal.name }}, {{terminal.city}}</span>
</mat-option>
</mat-autocomplete>
</form>
它工作正常,并且 span 指示我是否选择了一个对象(如果我自动编译对象,它会返回一个包含 id 的 json)。如何使用 select required 验证此字段?我接下来需要传递终端 ID,因此不选择应该是验证错误。谢谢!
解决方案
更新于 24-01-2019
根据@D 的评论。Make中需要自定义验证器功能input
。
所以,我更新了stackblitz上的代码。
我添加了一个名为 的新验证器forbiddenNamesValidator
,它允许用户仅从建议的值中输入名称。它已被添加到myControl
如下所示:
自动完成-简单-example.ts
...
constructor() {
this.myControl.setValidators(forbiddenNamesValidator(this.options));
}
...
export function forbiddenNamesValidator(names: string[]): 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 = names.findIndex(name => {
return (new RegExp('\^' + name + '\$')).test(control.value);
});
return index < 0 ? { 'forbiddenNames': { value: control.value } } : null;
};
}
html中的广告,处理如下:
...
<mat-error *ngIf="myControl.hasError('forbiddenNames')">
You should enter value from suggested one only. <strong>'{{myControl.errors.forbiddenNames.value}}'</strong> is not allowed.
</mat-error>
...
原始答案
要处理验证错误,您必须将其附加到input[required]
inside mat-form-field
:
<mat-form-field class="form-full-width">
<input type="text" matInput placeholder="Terminals" formControlName="terminal" required [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
<mat-option *ngFor="let terminal of (filteredTerminals)?.results" [value]="terminal">
<span>{{ terminal.name }}, {{terminal.city}}</span>
</mat-option>
</mat-autocomplete>
</mat-form-field>
您还可以在stackblitz上查看 Angular Material Team 的官方示例。
推荐阅读
- sql - 使用 T-SQL 为每个组查找前 25% 的客户
- python - 如何使用 argparse 将 AWS Sagemaker SM_USER_ARGS 解析为 argparse 命名空间?
- c++ - 矩阵类中的运算符重载函数有什么问题
- c# - 物品清单、库存系统、堆叠问题
- git - 当内容相同时,Git 声明文件已更改
- c# - ADODB.Recordset 到 C# 中的 JSON
- spring-batch - 在 Spring Batch 中展平列表列表的最佳方法是什么?
- ios - 有没有办法查看 WKWebView 何时可以使用 HTTPCookie?
- mysql - mysql #1054 使用 phpmyadmin 的未知列
- swift - 从 Firebase Firestore DB SWIFT UI 读取数据