Topic: How to use mdb-select-2 with reactive form AND mdb-select-filter

herve pro asked 3 years ago


I would like to use mdb-select-2 with search-box, within a reactive form. if I use the following code I have an error ( ngModel cannot be used to register form controls with a parent formGroup directive.)

<div class="md-form">
      <mdb-select-2 placeholder="Choose your option" label="Example label">
        <mdb-select-filter
          [ngModel]="searchText | async"
          (ngModelChange)="searchText.next($event)">
        </mdb-select-filter>
        <mdb-select-option *ngFor="let option of filteredOptions | async" [value]="option">{{ option.label }}</mdb-select-option>
      </mdb-select-2>
</div>

How can I mix search filter with reactive form ?

Without search filter I use the following code and it works :

<mdb-select-2 [outline]="true" id="listeRecette" [formControl]="compSelectRecette" placeholder="Sélectionnez une recette">
      <mdb-select-option *ngFor="let r of tabRecette"
               [value]="r.value">{{ r.label }}</mdb-select-option>
</mdb-select-2>

Thank you


Arkadiusz Idzikowski staff answered 3 years ago


Here is an example for reactive forms:

HTML:

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

TS:

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

  selectControl = new FormControl();

  ngOnInit() {
    this.filteredOptions = this.selectControl.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));
  }


Please insert min. 20 characters.

FREE CONSULTATION

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

Status

Answered

Specification of the issue

  • ForumUser: Pro
  • Premium support: No
  • Technology: MDB Angular
  • MDB Version: MDB4 10.1.1
  • Device: pc
  • Browser: chrome
  • OS: windows 10
  • Provided sample code: No
  • Provided link: No