我正在尝试使用新的控制流语法和材料的Mat-autocomplete在Angular 17中实现自动完成搜索。我只想在有搜索值时显示选项,但是当我添加此条件时,我会遇到选项选择功能破坏的问题。

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

条件可能会影响

@if
的内容投影,因此我们可以在可观察的级别进行过滤。

您可以使用

mat-option
angular angular-material
1个回答
0
投票

首先,我们创建一个可观察的名为

rxjs
,其中包含基于搜索值并搜索产品过滤的条件。
我们从
filteredOptions$

开始,然后对其进行管道,我们使用
products$

与形式控制值更改结合,然后应用三元条件以仅在存在搜索值时返回过滤的数据。

combineLatestWith

Full代码:

TS:

filteredOptions$: Observable<any[]> = this.products$.pipe( combineLatestWith(this.search.valueChanges), map(([products, value]: any) => { console.log(products, value); const filterValue = value?.toLowerCase(); return filterValue ? products.filter((product: any) => product.productCode?.toLowerCase()?.includes(filterValue) ) : []; }) );

Html:
import { Component, OnInit } from '@angular/core';
import { FormControl, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { Observable, of } from 'rxjs';
import { map, startWith, combineLatestWith } from 'rxjs/operators';
import { AsyncPipe, JsonPipe } from '@angular/common';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from '@angular/material/form-field';

/**
 * @title Filter autocomplete
 */
@Component({
  selector: 'autocomplete-filter-example',
  templateUrl: 'autocomplete-filter-example.html',
  styleUrl: 'autocomplete-filter-example.css',
  imports: [
    FormsModule,
    MatFormFieldModule,
    MatInputModule,
    MatAutocompleteModule,
    ReactiveFormsModule,
    AsyncPipe,
    JsonPipe,
  ],
})
export class AutocompleteFilterExample {
  search = new FormControl('');
  products$: Observable<Array<any>> = of([
    { productCode: 'one', brand: 'one', name: 'one' },
    { productCode: 'two', brand: 'two', name: 'two' },
    { productCode: 'three', brand: 'three', name: 'three' },
  ]);
  filteredOptions$: Observable<any[]> = this.products$.pipe(
    combineLatestWith(this.search.valueChanges),
    map(([products, value]: any) => {
      console.log(products, value);
      const filterValue = value?.toLowerCase();
      return filterValue
        ? products.filter((product: any) =>
            product.productCode?.toLowerCase()?.includes(filterValue)
          )
        : [];
    });
  );

  onSelect(e: any) {}

  resetProducts() {}
}

stackblitzdemo

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.