我正在尝试将Angular Material Component“突出显示第一个自动完成选项”用于使用来自API服务器的JSON数据的输入(它已经通过获取所有JSON数据来工作)。不知道我哪里错了。
我曾尝试使用 Angular Material 示例,但它使用硬编码方法,我需要来自 API 的数据
服务.ts
import { Appl } from '../intdets';
export class IntdetsService {
private url = "/assets/IntDet.json";
constructor(private http: HttpClient) { }
getName(): Observable<Appl[]> {
return this.http.get<Appl[]>(this.url);
}
}
intdets.ts
export class Appl {
_NAME: string;
}
JSON
{
"_APPLS": [
{
"_NAME": "some string",
},...]}
component.ts
export class IntdetsComponent implements OnInit {
public apps = [];
testCtrl: FormControl;
filteredTest: Observable<Appl[]>;
constructor(private _intdetsService: IntdetsService) {
this.testCtrl = new FormControl();
this.filteredTest = this.testCtrl.valueChanges
.pipe(
startWith(null),
switchMap(val => { return this.filterTest(val || '' )}));
}
filterTest(val: string) {
return this._intdetsService.getName().pipe(
map(res => res.filter(s => {
return s._NAME.toLowerCase().indexOf(val.toLowerCase()) === 0
}))
)
}
ngOnInit() {
this._intdetsService.getName()
.subscribe(data => {
this.apps = data;
console.log(data);
});
}
}
HTML
<mat-form-field >
<mat-label>Test Name</mat-label>
<input type="text" matInput [formControl]="testCtrl" [matAutocomplete]="autoTest">
<mat-autocomplete autoActiveFirstOption #autoTest="matAutocomplete">
<mat-option *ngFor="let test of filteredTest | async" [value]="test._APPLS">
{{test._NAME}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</p>