البحث بواسطة الـ Autocomplete

  classifications: CostsClassification[] = [];
  icons: any[] = [];
  _icons: any[] = [];
  filteredIcons: Observable<any[]>;

  form = this._formBuilder.group({
    parent_mode: (this.data?.id) ? [''] : ['', Validators.required],
    ar_name: ['', Validators.required],
    en_name: ['', Validators.required],
    parent: ['', Validators.required],
    icon: ['', Validators.required]
  });

  constructor(public translateService: TranslateService,
    private _formBuilder: FormBuilder,
    public googleTranslateService: _GoogleTranslateService,
    private ingredientsClassificationsService: CostsClassificationsService,
    private materialIconsService: _MaterialIconsService,
    @Inject(MAT_DIALOG_DATA) public data: CostsClassification,
  ) {
    this.filteredIcons = this.form.controls['icon'].valueChanges.pipe(
      startWith(''),
      map(value => this._filter(value))
    );

    this.materialIconsService.getItems().subscribe(res => {
      this.icons = res;
      res.forEach(element => {
        for (let item of element.icons) {
          this._icons.push(item);
        }
      });
      console.log(this._icons);
    });
    if (this.data) {
      this.ingredientsClassificationsService.getOne(this.data.id).subscribe(res => {
        this.data = res;
      });
    } else {
      this.data = new CostsClassification();
    }
    this.refresh();
  }

  private _filter(value: string): string[] {
    if (value) {
      const filterValue = value.toLowerCase();
      return this._icons.filter(option => option.keywords.join(', ').toLowerCase().includes(filterValue));
    } {
      return this._icons;
    }
  }


الـ HTML

div class="col-12 col-md-6 mt-2">
                    <mat-form-field class="w-100" appearance="outline">
                        <mat-label>{{'LABELS.ICON' | translate}}</mat-label>
                        <input #icon formControlName="icon" [(ngModel)]="data.icon"
                            maxlength="50" matInput type="text" maxlength="20"
                            onkeyup="return this.value=this.value.toLowerCase();"
                            [placeholder]="'PLACEHOLDERS.ICON' | translate" [matAutocomplete]="!data.icon? autoFilter : autoGroup" required>
                        <mat-hint>
                            <a href="https://fonts.google.com/icons" target="_blank">{{'LINKS.BROWSE_ICONS' |
                                translate}}</a>
                        </mat-hint>
                        <mat-hint align="end">{{icon.value.length}}/20</mat-hint>
                        <mat-icon class="icon-color" *ngIf="icon.value.length !== 0" matSuffix>{{data.icon}}</mat-icon>
                        <mat-error align="start" *ngIf="form.controls['icon'].hasError('required')">
                            {{'ERRORS.REQUIRED' | translate}}
                        </mat-error>

                        <mat-autocomplete #autoFilter="matAutocomplete">
                            <mat-option *ngFor="let item of filteredIcons | async" [value]="item.ligature">
                                <mat-icon class="icon-edit">{{ item.ligature }}</mat-icon>{{ item.name
                                }}</mat-option>
                        </mat-autocomplete>
                    </mat-form-field>
                </div>


السؤال: filter in mat-option with mat-autocomplete in angular

التوثيق: 

To filter mat-option items within a mat-autocomplete in Angular, you can use Angular's reactive forms and RxJS operators to create a dynamic filtering mechanism. Here's a step-by-step guide to achieve this:

Step 1: Set Up Your Angular Component

  1. Import necessary modules in your app.module.ts.
typescript
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { ReactiveFormsModule } from '@angular/forms'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; import { MatAutocompleteModule } from '@angular/material/autocomplete'; import { MatOptionModule } from '@angular/material/core'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, MatFormFieldModule, MatInputModule, MatAutocompleteModule, MatOptionModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
  1. Create the component and set up the form control and the options array.
typescript
import { Component, OnInit } from '@angular/core'; import { FormControl } from '@angular/forms'; import { Observable } from 'rxjs'; import { map, startWith } from 'rxjs/operators'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { myControl = new FormControl(); options: string[] = ['Apple', 'Orange', 'Banana', 'Grapes', 'Mango']; filteredOptions: Observable<string[]>; ngOnInit() { this.filteredOptions = this.myControl.valueChanges.pipe( startWith(''), map(value => this._filter(value)) ); } private _filter(value: string): string[] { const filterValue = value.toLowerCase(); return this.options.filter(option => option.toLowerCase().includes(filterValue)); } }

Step 2: Create the Template

Define the template to use mat-autocomplete with mat-option.

html
<!-- app.component.html --> <mat-form-field> <input matInput [formControl]="myControl" [matAutocomplete]="auto"> <mat-autocomplete #auto="matAutocomplete"> <mat-option *ngFor="let option of filteredOptions | async" [value]="option"> {{ option }} </mat-option> </mat-autocomplete> </mat-form-field>

Explanation:

  1. Component Setup:

    • myControl: FormControl for the input field.
    • options: Array of string options to be filtered.
    • filteredOptions: Observable that holds the filtered options based on the input value.
  2. Filtering Logic:

    • ngOnInit(): Initializes the filteredOptions observable, which listens to changes in the input field and applies the _filter method.
    • _filter(value: string): Filters the options array based on the input value, converting both the input and options to lowercase for case-insensitive matching.
  3. Template:

    • The template includes mat-autocomplete with mat-option to display the filtered options. The *ngFor directive iterates over the filtered options and displays them as autocomplete suggestions.

Dynamic Filtering:

Whenever the user types in the input field, the myControl.valueChanges observable emits a new value, triggering the _filter method. This method filters the options array and updates the filteredOptions observable, which in turn updates the displayed autocomplete suggestions.

This approach ensures that your mat-autocomplete dynamically filters the mat-option items based on the user's input, providing a smooth and responsive autocomplete experience.















 

تعليقات

المشاركات الشائعة من هذه المدونة

ngx-extended-pdf-viewer

how to getting access token for https://fcm.googleapis.com/v1/projects/al-ayahya-co/messages:send for angular and backend nestjs

طريقة تفعيل زر Inline Keyboard في Telegram Bot