无法使用下拉菜单中的搜索过滤器以初始值显示mat-select

问题描述 投票:0回答:2

我正在尝试使用Angular material and Ng2SearchPipeModule在angular2或更高版本中实现在MatSelect下拉列表中的搜索过滤器,但我遇到了一些问题。我需要

  1. 默认显示选择标记中的第一个元素
  2. 当我在搜索框中搜索任何内容时,应将其过滤掉
  3. 如果我在搜索框中搜索任何内容后未在matselect中选择任何内容,则当我关闭下拉菜单时,先前选择的选项应该在Matdropdown中可见。

现在,当我第一次加载页面时,我的搜索过滤器也可以正常工作,默认情况下,我可以在Matselect中看到第一个元素。

但是当我在搜索框中搜索任何内容然后关闭下拉菜单时,我的matselect将为空白,此后,当我再次打开matselect下拉菜单时,搜索框仍然显示文本。控制台中也没有任何错误。

因此,我希望当我搜索任何内容而不选择任何下拉菜单时,它应该具有先前选择的菜单,而当我关闭并重新打开时,下拉菜单搜索框应该是清除的

component.html'

  <mat-form-field>
          <mat-select [(ngModel)]="myValue">
              <input type="text" [(ngModel)]="term">
              <mat-option *ngFor="let o of allValues  | filter:myValue" 
              value="{{o.name}}">

            {{o.name}}{{o.id}}
            </mat-option>
          </mat-select>
     </mat-form-field>

          <p> Selected value: {{myValue}} </p>

component.ts

term=''

  AllValues =[{
    id:1,
    name:'ashita ',
    description:'description 1'
  },{
    id:2,
    name:'deepak ',
    description:'description 2'
  },{
    id:3,
    name:'rahul 3',
    description:'description 3'
  }]

  allValues = this.AllValues;

  myValue: any = this.AllValues[0].name 

image1image2

但是问题出在最后一张显示空结果的图像中problem

angular filter angular-material materialize angular8
2个回答
0
投票

https://stackblitz.com/edit/mat-select-search?file=app%2Fapp.component.html中获取参考,然后分析您的问题,我修改了代码并为您简化了代码

component.html

<mat-form-field>
      <mat-select [formControl]="bankCtrl" placeholder="Bank" >
        <mat-select-search [formControl] ="bankFilterCtrl"  [(ngModel)]="term"></mat-select-search>
        <mat-option *ngFor="let bank of filteredBanks | async | filter:term" [value]="bank">
          {{bank.name}}
        </mat-option>
      </mat-select>
    </mat-form-field>

component.ts

export class AppComponent implements OnInit{ 

  public bankCtrl: FormControl = new FormControl();
  public bankFilterCtrl: FormControl = new FormControl();
 public filteredBanks: ReplaySubject<any[]> = new ReplaySubject<any[]>(1);


  private banks  = [
   {
    id:1,
    name:'ashita ',
    description:'description 1'
  },{
    id:2,
    name:'deepak ',
    description:'description 2'
  },{
    id:3,
    name:'rahul 3',
    description:'description 3'
  }
  ]


term='';


  ngOnInit() {
    // set initial selection
    this.bankCtrl.setValue(this.banks[1]);

    // load the initial bank list
    this.filteredBanks.next(this.banks.slice());


  }
}

检查一下,让我知道!


0
投票

我认为您为过滤器管道选择了错误的变量:)

此行:

                                                   Here
                                                 \/\/\/\/
<mat-option *ngFor="let o of allValues  | filter:myValue" value="{{o.name}}">

成为:

<mat-option *ngFor="let o of allValues  | filter: term" value="{{o.name}}">

Working_Demo

© www.soinside.com 2019 - 2024. All rights reserved.