angular - 根据条件更改 mat-autocomplete 选项的值,并过滤这些选项
问题描述
我正在尝试让用户在输入中输入至少 3 个字符后出现 mat-options。当输入的长度小于 3 时,选项数组将为空。如果输入的长度大于 2,那么我可以在数组中赋值。
另外,我希望在用户写入输入时过滤结果。
我已经设法过滤了结果(使用材料文档),并且如果输入的长度大于 2,我还设法更改了选项的值。但我不能让两者都有相同的时间。
这是我的组件的代码:
export class FormComponent implements OnInit {
myForm!: FormGroup;
options: string[] = null;
filteredOptions: Observable<string[]>;
constructor(private fb: FormBuilder) {}
ngOnInit(): void {
this.myForm = this.fb.group({ myControl: ['', [Validators.required]] });
this.filteredOptions = this.filterOption(this.myControl, this.options);
}
updateOptions() {
let controlLength: number = this.myControl.value.length;
if (controlLength === 3) this.options = ['Stack', 'Overflow', 'isAwesome'];
else if (controlLength < 3) this.options = [''];
}
filterOption(control: AbstractControl, controlOptions: string[]) {
return control.valueChanges.pipe(
startWith(''),
map((controlValue) => this._filter(controlValue, controlOptions))
);
}
private _filter(controlValue: string, controlOptions: string[]): string[] {
return controlOptions?.filter((option) =>
option.toLowerCase().includes(controlValue.toLowerCase())
);
}
get myControl() {
return this.myForm.get('myControl');
}
displayFn(subject) {
return subject ? subject.name : undefined;
}
这是我的组件的 html:
<mat-form-field>
<mat-label>My Input <span class="required">*</span></mat-label>
<input
matInput
type="text"
formControlName="myControl"
[matAutocomplete]="auto"
(input)="updateOptions()"
/>
<mat-autocomplete #auto >
<mat-option *ngFor="let option of filteredOptions | async" [value]="option">
{{ option }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
先感谢您!
解决方案
推荐阅读
- regex - The passing of a string (incl. regex parameters) to a block of code
- jmeter-5.0 - 如何在 Json 中获取值,其中键具有另一个有效负载形式的值
- html - 每当浏览器尺寸减小和使用 CSS / JSS 数据溢出时,在 HTML 的 div 标签上启用滚动条
- powerbi - Power BI 中动态变化的排名列
- r - 访问 Rcpp 中的列表列表
- pandas - 使用 Streamz 从 pandas DataFrame 流式传输
- sql - “OR”运算符与“AND”运算符的表要求有何不同?
- google-cloud-platform - BigQuery:获取某个时间点的离线用户以及他们离线的时间
- javascript - 无法正确解析通过网络发送的字符串化 Json
- ios - 使用 SwiftUI 的 TabbedView 切换到其他选项卡时查看内容不显示