在Angular的mat-autocomplete中,可以通过以下步骤来实现在setValue后突出显示选项值:
<input type="text" matInput [formControl]="myControl" [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let option of filteredOptions | async" [value]="option">
{{ option }}
</mat-option>
</mat-autocomplete>
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { startWith, map } from 'rxjs/operators';
@Component({
selector: 'app-autocomplete',
templateUrl: './autocomplete.component.html',
styleUrls: ['./autocomplete.component.css']
})
export class AutocompleteComponent {
myControl = new FormControl();
options: string[] = ['Option 1', 'Option 2', 'Option 3'];
filteredOptions: Observable<string[]>;
constructor() {
this.filteredOptions = this.myControl.valueChanges.pipe(
startWith(''),
map(value => this._filter(value))
);
}
private _filter(value: string): string[] {
const filterValue = value.toLowerCase();
return this.options.filter(option => option.toLowerCase().includes(filterValue));
}
}
import { Component, ViewChild } from '@angular/core';
import { MatAutocompleteTrigger } from '@angular/material/autocomplete';
@Component({
selector: 'app-autocomplete',
templateUrl: './autocomplete.component.html',
styleUrls: ['./autocomplete.component.css']
})
export class AutocompleteComponent {
@ViewChild(MatAutocompleteTrigger) trigger: MatAutocompleteTrigger;
// ...
setValueAndHighlight(option: string) {
this.myControl.setValue(option);
setTimeout(() => {
this.trigger.openPanel();
});
}
}
通过以上步骤,当调用setValueAndHighlight()方法设置输入框的值后,选项值将会被突出显示。请注意,这里的代码示例是基于Angular Material库实现的,如果你想了解更多关于Angular Material的信息,可以访问腾讯云的相关产品和产品介绍链接地址。
领取专属 10元无门槛券
手把手带您无忧上云