Holiday Notice: Support will be provided on a limited scale from December 24th, 2024, to January 2nd, 2025. Happy holidays and a wonderful New Year!


Topic: Select search box Angular reactive forms

ARcode pro asked 4 years ago


Expected behavior Basic searchbox inside the mdb-select-2 component using reactive forms.

Actual behavior The current search box shown in the mdb-select-2 documentation (here) is based on ngModel, which is imcompatible with reactive forms working on the same component.

Is there a way to implement the search box in a select element that uses reactive forms?

Thanks


Arkadiusz Idzikowski staff answered 4 years ago


You need to create new Angular FormControl and listen to its valueChange method. Here is an example:

HTML:

<div class="md-form">
  <mdb-select-2 placeholder="Choose your option" label="Example label">
    <mdb-select-filter
      [formControl]="searchInput">
    </mdb-select-filter>
    <mdb-select-option *ngFor="let option of filteredOptions | async" [value]="option">{{ option.label }}</mdb-select-option>
  </mdb-select-2>
</div>

TS:

  searchInput = new FormControl('');
  filteredOptions: Observable<any[]>;
  options = [
    { value: '1', label: 'Option 1' },
    { value: '2', label: 'Option 2' },
    { value: '3', label: 'Option 3' },
  ];

  ngOnInit() {
    this.filteredOptions = this.searchInput.valueChanges.pipe(
      startWith(''),
      map((value: string) => this.filter(value))
    );
  }

  filter(value: string): any[] {
    const filterValue = value.toLowerCase();
    return this.options.filter((option: any) => option.label.toLowerCase().includes(filterValue));
  }

ARcode pro commented 4 years ago

Thanks it works perfectly!



Please insert min. 20 characters.

FREE CONSULTATION

Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.

Status

Resolved

Specification of the issue

  • ForumUser: Pro
  • Premium support: No
  • Technology: MDB Angular
  • MDB Version: 10.0.0
  • Device: Computer
  • Browser: Chrome
  • OS: Windows
  • Provided sample code: No
  • Provided link: Yes