Angular的mat-autocomplete在我使用formcontrolname而不是[formcontrol]时无法过滤值。
创始人
2024-10-24 07:01:06
0

要解决Angular中使用mat-autocomplete时,在使用formControlName而不是[formControl]时无法过滤值的问题,可以按照以下步骤进行操作:

  1. 在使用formControlNameinput元素上添加[matAutocomplete]指令,并将其绑定到一个模板变量上,例如autocomplete

  1. input元素之后添加mat-autocomplete组件,并将其绑定到与matAutocomplete指令相同的模板变量上:


  

  1. 在组件类中,使用ViewChild装饰器来获取mat-autocomplete组件的引用,并将其与formControlName关联起来:
import { Component, ViewChild } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MatAutocomplete } from '@angular/material/autocomplete';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
})
export class ExampleComponent {
  myControl = new FormControl();
  @ViewChild(MatAutocomplete) autocomplete: MatAutocomplete;
}
  1. 最后,在ngOnInit生命周期钩子中,订阅formControl的值变化,并使用filter方法过滤mat-autocomplete选项的值:
import { Component, OnInit, ViewChild } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MatAutocomplete } from '@angular/material/autocomplete';
import { startWith, map } from 'rxjs/operators';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {
  myControl = new FormControl();
  @ViewChild(MatAutocomplete) autocomplete: MatAutocomplete;

  ngOnInit() {
    this.myControl.valueChanges
      .pipe(
        startWith(''),
        map(value => this._filter(value))
      )
      .subscribe(filteredOptions => {
        // 更新mat-autocomplete的选项
        this.autocomplete.options = filteredOptions;
      });
  }

  private _filter(value: string): string[] {
    // 过滤逻辑,根据value返回过滤后的选项数组
    // 例如,从一个选项数组中过滤出与value匹配的选项
    const filterValue = value.toLowerCase();
    return this.options.filter(option => option.toLowerCase().includes(filterValue));
  }
}

以上步骤中,options是一个字符串数组,用于存储mat-autocomplete的选项。根据具体需求,你可以将options替换为自己的选项数组。

通过上述步骤,你应该能够使用formControlName来过滤mat-autocomplete的值。

相关内容

热门资讯

有玩家发现!aapoker怎么... 有玩家发现!aapoker怎么控制牌,德普之星透视辅助软件是真的吗,好像是真的有挂(有挂存在)1、游...
重大通报!吉祥填大坑有什么诀窍... 重大通报!吉祥填大坑有什么诀窍,天天开心王国有没有挂,详细技巧(有挂教程)1、天天开心王国有没有挂免...
一直以来!微扑克游戏辅助器,如... 一直以来!微扑克游戏辅助器,如何下载德普之星辅助软件,好像确实有挂(新版有挂)1、每一步都需要思考,...
重大通报!金虎爷辅助插件,微乐... 重大通报!金虎爷辅助插件,微乐卡五星祈福有用吗,详细技巧(有挂方法)1)微乐卡五星祈福有用吗有没有挂...
据权威媒体报道!wepoker... 据权威媒体报道!wepoker私人局怎么玩,德普之星的辅助工具介绍,真是是真的有挂(有挂分析)1)德...
一分钟了解!决战卡五星辅助io... 一分钟了解!决战卡五星辅助ios,海商嘟咪互动辅助,详细技巧(有挂分享)1、游戏颠覆性的策略玩法,独...
反观!哈糖大菠萝有挂吗5个常用... 反观!哈糖大菠萝有挂吗5个常用方法,德普辅助软件,真是真的是有挂(有挂工具)1、打开软件启动之后找到...
今日科普!微乐家乡app下载,... 今日科普!微乐家乡app下载,微乐游戏辅助脚本安卓,详细方法(了解有挂)1、金币登录送、破产送、升级...
近期!哈糖大菠萝辅助器,德扑之... 近期!哈糖大菠萝辅助器,德扑之星辅助器怎么用,切实是真的有挂(有挂攻略)1)德扑之星辅助器怎么用辅助...
发现一款!凑一桌游戏关春天辅助... 发现一款!凑一桌游戏关春天辅助,红人阁自动挂机脚本,详细工具(确实有挂)1、下载好凑一桌游戏关春天辅...