Angularmat-autocomplete无法使用通过函数返回的选项。
创始人
2024-10-28 06:31:05
0

在使用mat-autocomplete时,如果选项是通过调用函数来返回的,则需要在函数返回之前将选项放入一个数组中。这样mat-autocomplete才能够正确地使用它们。

以下是示例代码:

在component.ts文件中,定义一个函数来返回选项。该函数首先调用一个API来获取选项,然后将选项放入数组中,最后返回该数组:

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { map } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  optionList: any[] = [];

  constructor(private http: HttpClient) {}

  getOptions(keyword: string): Observable {
    return this.http.get(`https://api.example.com/options?keyword=${keyword}`).pipe(
      map((result: any) => {
        this.optionList = result.options; // 将选项放入数组中
        return this.optionList;
      })
    );
  }
}

在component.html文件中,使用mat-autocomplete时,使用ng-template对返回的选项进行循环。这里的options是一个本地变量,它保存了mat-autocomplete使用的选项数组。然后,调用getOptions函数来获取选项:


  
  
    
      {{ option }}
    
  

然后,在component.ts文件中,在函数返回中调用mat-autocomplete的update方法,传递选项数组作为参数:

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { map } from 'rxjs/operators';
import { MatAutocomplete } from '@angular/material';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  optionList: any[] = [];

  constructor(private http: HttpClient) {}

  getOptions(keyword: string, autocomplete: MatAutocomplete): Observable {
    return this.http.get(`https://api.example.com/options?keyword=${keyword}`).

相关内容

热门资讯

8分钟诀窍!wepoker辅助... 您好,wepoker辅助器有哪些功能这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275...
四分钟法子!wpk透视是真的假... 四分钟法子!wpk透视是真的假的(透视)都是是有辅助神器(哔哩哔哩)wpk透视是真的假的辅助器是一种...
第七分钟总结!hhpoker有... 第七分钟总结!hhpoker有后台操作吗(透视)果然是有辅助教程(哔哩哔哩)1、该软件可以轻松地帮助...
第六分钟手段!黑侠破解wepo... 第六分钟手段!黑侠破解wepoker(透视)真是是有辅助辅助(哔哩哔哩)1、打开软件启动之后找到中间...
3分钟讲义!wepoker分析... 3分钟讲义!wepoker分析(透视)真是真的是有辅助教程(哔哩哔哩)1、这是跨平台的wepoker...
第1分钟妙招!poker wo... 第1分钟妙招!poker world辅助(透视)本来真的是有辅助开挂(哔哩哔哩)1、下载好poker...
第十分钟方式!wepokerp... 第十分钟方式!wepokerplus到底是挂了吗(透视)切实存在有辅助脚本(哔哩哔哩)1、操作简单,...
两分钟法子!hhpoker辅助... 两分钟法子!hhpoker辅助(透视)确实是有辅助开挂(哔哩哔哩)亲,关键说明,hhpoker辅助透...
第九分钟窍要!模拟器打开hhp... 第九分钟窍要!模拟器打开hhpoker(透视)竟然真的是有辅助开挂(哔哩哔哩)在进入模拟器打开hhp...
五分钟学习!wepoker有辅... 五分钟学习!wepoker有辅助功能吗(透视)总是存在有辅助神器(哔哩哔哩)1、wepoker有辅助...