gpt4 book ai didi

angular - 避免 Angular Material Autocomplete display mat-options 当它为空时

转载 作者:搜寻专家 更新时间:2023-10-30 21:36:23 27 4
gpt4 key购买 nike

我开始在我的一个项目中使用 Material。查看 <mat-autocomplete> 的示例文档网站...

<mat-form-field class="example-full-width">
<input matInput placeholder="State" aria-label="State" [matAutocomplete]="auto" [formControl]="stateCtrl">
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let state of filteredStates | async" [value]="state.name">
<span>{{state.name}}</span> |
</mat-option>
</mat-autocomplete>

:

    export class AutocompleteOverviewExample {        
stateCtrl = new FormControl();
filteredStates: Observable<State[]>;
states: State[] = [
{ name: 'Arkansas' },
...
{ name: 'Texas' }
];

constructor() {
this.filteredStates = this.stateCtrl.valueChanges
.pipe(
startWith(''),
map(state => state ? this._filterStates(state) : this.states.slice())
);
}

private _filterStates(value: string): State[] {
const filterValue = value.toLowerCase();
return this.states.filter(state => state.name.toLowerCase().indexOf(filterValue) === 0);

// Material example, its basically a ._http.get(value).map
}
}

<mat-option>在输入字段中单击时列出其已部署。我想避免这种情况,只在 X 时显示选项(他们写了 3 个或更多字符,它是一个包含 5 或 10 个元素的“小”列表,等等)。

如何修改此行为并动态执行?

最佳答案

这是库中的默认行为。要自定义它,您只需在更改自动完成的模型值时使用 CSS 隐藏自动完成选项,然后设置您希望在输入文本上具有的最小长度,然后相应地显示自动完成选项。将 View 代码更新为:

<mat-form-field class="example-full-width">
<input matInput placeholder="State" aria-label="State" [matAutocomplete]="auto" [formControl]="stateCtrl"
(ngModelChange)="updatedVal($event)">
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let state of filteredStates | async" [value]="state.name"
[ngClass]="{'hide-autocomplete': !showAutocomplete}">
<span>{{state.name}}</span> |
</mat-option>
</mat-autocomplete>
</mat-form-field>

在这里,我在输入字段上添加了 ngModelChange 以检查模型更改。在 mat-option 上我添加了 ngClass。在哪里

.hide-autocomplete { display: none; }

在类中,updatedVal 方法是:

updatedVal(e) {
if(e && e.length >= 3) {
this.showAutocomplete = true;
} else {
this.showAutocomplete = false;
}
}

只有当输入长度小于 3 时,隐藏类才会被添加到 mat-option。

Demo Example

关于angular - 避免 Angular Material Autocomplete display mat-options 当它为空时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51221170/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com