Tal*_*ode 13 typescript angular-material angular
我正在使用material.angular.io中的mat-auto完整组件.默认行为是用户可以输入任何值,并提供可供选择的选项.您还可以将输入添加到所选值.你可以在这里查看示例. https://stackblitz.com/angular/ngmvgralayd?file=app%2Fautocomplete-simple- example.html
这是我用于生成自动完成输入字段的代码.
<form class="example-form">
<mat-form-field class="example-full-width">
<input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto" disabled="true">
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let option of options" [value]="option">
{{ option }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>
Run Code Online (Sandbox Code Playgroud)
但我希望表单字段仅从给定选项中获取值,并希望除了给定选项之外,不希望用户输入任何值.怎么做到这一点?它就像具有自动完成功能的选择输入.
在github上找到了这个解决方案,它可能为那些最终来到这里的人提供了一个简单的替代方案。
创建自定义验证器:
private requireMatch(control: FormControl): ValidationErrors | null {
const selection: any = control.value;
if (this.options && this.options.indexOf(selection) < 0) {
return { requireMatch: true };
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
将它附加到您的控件上(我们需要将它绑定到 this 以便我们的验证器可以访问我们组件范围内的选项)
myControl = new FormControl(undefined, [Validators.required, this.requireMatch.bind(this)]);
Run Code Online (Sandbox Code Playgroud)
可选显示错误:
<mat-error *ngIf="myControl.errors?.requireMatch">Value need match available options</mat-error>
Run Code Online (Sandbox Code Playgroud)
这里的例子-----------> https://stackblitz.com/edit/angular-hph5yz
你可以做这样的事情
标记:
<md-input-container class="full-width">
<input mdInput [mdAutocomplete]="autoData"
#searchMyData
formControlName="myControl"
(keyup)="changeMyControl()">
</md-input-container>
<md-autocomplete #autoData="mdAutocomplete">
<md-option
*ngFor="let option of options"
[value]="option.name"
(onSelectionChange)="onSelectedOption($event.source.selected, option.id);">
{{ option.name }}
</md-option>
</md-autocomplete>
Run Code Online (Sandbox Code Playgroud)
零件:
selectedOption;
changeMyControl(): void {
if (isUndefined(this.selectedOption) {
// also check selected item and entered text are not same
this.myForm.get('myControl').setErrors({'incorrect': true});
}
}
onSelectedOption(isSelected: boolean, id: number): void {
if (isSelected) {
setTimeout(() => {
const option = this.options.filter(bt => bt.id === id);
if (option.length > 0) {
this.selectedOption= option[0];
// patch formcontrol value here
}
}, 200);
}
}
Run Code Online (Sandbox Code Playgroud)
正如 @tricheriche 的评论中已经建议的,这是 select 的一个用例。
您可以使用 select 的材质版本,如下所示
<mat-form-field>
<mat-select placeholder="Favorite food">
<mat-option *ngFor="let food of foods" [value]="food.value">
{{ food.viewValue }}
</mat-option>
</mat-select>
</mat-form-field>
Run Code Online (Sandbox Code Playgroud)
如果您需要在选择上方进行过滤,我建议您使用 PrimeNg Dropdown https://www.primefaces.org/primeng/#/dropdown
| 归档时间: |
|
| 查看次数: |
8648 次 |
| 最近记录: |