我有一个下拉列表,可以获取一些json数据。我通过获取所有API来获取数据。所以我还没有对任何数据进行硬编码。我正在用角度
<td>
<mat-form-field>
<mat-label>Customer</mat-label>
<mat-select formControlName="custom">
<mat-option *ngFor="let customer of customerList" [value]="customer.id">
{{customer.name}}
</mat-option>
</mat-select>
</mat-form-field>
</td>
所以在这里,我有一个名为customerList的列表,其中的数据为json格式。因此,我必须在下拉菜单中显示名称字段,并将ID传递给后端。因此,我的任务是对该下拉列表进行自动填充搜索
答案 0 :(得分:0)
您可以使用Angular Material中的AutoComplete。
<mat-form-field class="example-full-width">
<input type="text"
placeholder="Pick one"
aria-label="Number"
matInput
[formControl]="myControl"
[matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let option of filteredOptions | async" [value]="option">
{{option}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
在组件中,您可以编写自己的过滤器逻辑
filteredOptions: Observable<string[]>;
ngOnInit() {
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));
}
答案 1 :(得分:0)
@Joe Rishwanth您需要添加mat-autocomplete
进行下拉
您的客户列表的HTML文件:
<form class="example-form">
<mat-form-field>
<input type="text"
placeholder="Enter Customer name"
aria-label="Number"
matInput
[formControl]="custom"
[matAutocomplete]="auto">
<mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
<mat-option *ngFor="let customer of customerFilter | async" [value]="customer">
{{customer.name}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
Ts文件:
export class AutocompleteAutoActiveFirstOptionExample implements OnInit {
custom = new FormControl();
customerList = [{ id: 1, name: "kumar" }, { id: 2, name: "mukesh" }];
customerFilter: Observable<any>;
ngOnInit() {
this.customerFilter = this.custom.valueChanges.pipe(
startWith(""),
map(value => this._filter(value))
);
}
private _filter(value: string): any {
const filterValue = value;
return this.customerList.filter(customer => {
return customer.name.toLowerCase().indexOf(filterValue) === 0;
});
}
}
关于堆栈闪电的参考文献:https://stackblitz.com/edit/angular-ih4c5r?file=src%2Fapp%2Fautocomplete-auto-active-first-option-example.ts