0
votes

I have searched for a filtered dropdown option in angular material and could not find anything with mat-select multiselect. I don't think an implementation is available in angular material for mat-select. Is there a way to implement this using angular material?

3
the autocomplete is used with mat-option elemet as a list. I have a mat-select element multiple select option. Can I use the filter with mat-select?Thomas John
I don't know about angular material but there is one in PrimeNG, it's a really good ui components libary for angularLagistos
Mat select search github.com/bithost-gmbh/ngx-mat-select-search could be an option ?Yin

3 Answers

1
votes

Well, We can create a material input form control that was a multiselect with filter.

As the answer is a bit larger, you can see the result in the stackblitz

The idea is that we has a component that has a @input that can be an array of strings or an array of object. We has three auxiliars variables

  _list: any[]; //<--an array of object
  keys: string[]; //an array with two values, the "key" and the "text"
  listFiltered: any[]; //<--the list above filtered

And two formControls, one to show the value and one to filter the list

  control = new FormControl();
  search = new FormControl();

When we received the list in a input we create the _list and give value to keys

  @Input() set list(value) {
    this._list =
      typeof value[0] == "string"
        ? value.map(x => ({ key: x, value: x }))
        : [...value];
    this.keys = Object.keys(this._list[0]);

So, e.g.

list: any[] = [
    {id:1,name:"Extra cheese"},
    {id:2,name:"Mushroom"},
    {id:3,name:"Onion"},
    {id:4,name:"Pepperoni"},
    {id:5,name:"Sausage"},
    {id:6,name:"Tomato"}
  ];
_list=[...list]
keys[0]="id"; keys[1]="name"

if

list=["Extra cheese","Mushroom","Onion","Pepperoni",name:"Sausage","Tomato"}
_list will be
        {key:"Extra cheese",value:"Extra cheese"},
        {key:"Mushroom",value:"Mushroom"},
        {key:"Onion",value:"Onion"},
        {key:"Pepperoni",value:"Pepperoni"},
        {key:"Sausage",value:"Sausage"},
        {key:"Tomato",value:"Tomato"}
 and 
    keys[0]="key"; keys[1]="value"

This allow us create a component that has a formControl and a "menu"

<div class="multi-select">
      <input (click)="trigger.openMenu()" readonly [formControl]="control" />
      <span #menu class="mat-select-wrapper" [matMenuTriggerFor]="appMenu" (menuOpened)="searchID.focus()">
        <span class="mat-select-arrow"> </span>
      </span>
    </div>
    <mat-menu #appMenu="matMenu" xPosition="before">
      <div class="menu" (click)="$event.stopPropagation()">
        <mat-form-field>
          <mat-label>Search</mat-label>
          <input #searchID matInput placeholder="search" [formControl]="search" />
        </mat-form-field>
        <div class="mat-menu-item" *ngFor="let item of listFiltered">
          <mat-checkbox
            [checked]="item.checked"
            (change)="change($event.checked, item[keys[0]])"
          >
            {{ item[keys[1]] }}</mat-checkbox
          >
        </div>
      </div>
    </mat-menu>

We need use a ViewChild to open the menu when the control is focused

@ViewChild(MatMenuTrigger, { static: false }) trigger: MatMenuTrigger;

If we use in ngOnInit

    this.search.valueChanges
      .pipe(
        startWith(null),
        delay(200)
      )
      .subscribe(res => {
        const search = res ? res.toLowerCase() : "";
        this.listFiltered = this._list.filter(
          x => !res || x.checked ||
                x[this.keys[1]].toLowerCase().indexOf(search) >= 0
        );
      });
  }

An a function (change)

change(value, key) {
    const item = this._list.find(x => x[this.keys[0]] == key);
    item.checked = value;
  }

when we change the search, the listFiltered contains the elements of the control and the elements that containst the value, and this._list will be an array with elements that has a property "checked" that becomes true if selected.

Well, Now the difficult part is convert to a mat custom form control. We need follow the guide in the docs

In brief, we need add a provider and host some classes

  providers: [
    { provide: MatFormFieldControl, useExisting: MultiSelectFilterComponent }
  ],
  host: {
    "[class.example-floating]": "shouldLabelFloat",
    "[id]": "id",
    "[attr.aria-describedby]": "describedBy"
  }

In constructor inject FocusMonitor,ElementRef and ngControl

  constructor(
    private _focusMonitor: FocusMonitor,
    private _elementRef: ElementRef<HTMLElement>,
    @Optional() @Self() public ngControl: NgControl
  ) {
    _focusMonitor.monitor(_elementRef, true).subscribe(origin => {
      if (this.focused && !origin) {
        this.onTouched();
      }
      this.focused = !!origin;
      this.stateChanges.next();
    });

    if (this.ngControl != null) {
      this.ngControl.valueAccessor = this;
    }
  }

Add somes variables and Inputs

  controlType = "multi-select-filter";
  static nextId = 0;
  static ngAcceptInputType_disabled: boolean | string | null | undefined;
  id = `multi-select-filter-${MultiSelectFilterComponent.nextId++}`;
  describedBy = "";
  onChange = (_: any) => {};
  onTouched = () => {};

  stateChanges = new Subject<void>();
  focused = false;
  get errorState() //<----This is IMPORTANT, give us if the control is valid or nor
  {
      return this.ngControl?this.ngControl.invalid && this.ngControl.touched:false;
  } 
  get empty() {
    return !this.control.value;
  }
  get shouldLabelFloat() {
    return this.focused || !this.empty;
  }
  @Input()
  get placeholder(): string {
    return this._placeholder;
  }
  set placeholder(value: string) {
    this._placeholder = value;
    this.stateChanges.next();
  }
  private _placeholder: string;

  @Input()
  get required(): boolean {
    return this._required;
  }
  set required(value: boolean) {
    this._required = coerceBooleanProperty(value);
    this.stateChanges.next();
  }
  private _required = false;

  @Input()
  get disabled(): boolean {
    return this._disabled;
  }
  set disabled(value: boolean) {
    this._disabled = coerceBooleanProperty(value);
    this._disabled ? this.control.disable() : this.control.enable();
    this.stateChanges.next();
  }
  private _disabled = false;

  @Input()
  get value(): any[] | null {  //<--this is the value of our control
    if (!this._list) return null; //In my case we return an array based in 
                                  //this._list
    const result = this._list.filter((x: any) => x.checked);
    return result && result.length > 0
      ? result.filter(x => x.checked).map(x => x[this.keys[0]])
      : null;
  }
  set value(value: any[] | null) {
    if (this._list && value) {
      this._list.forEach(x => {
        x.checked = value.indexOf(x[this.keys[0]]) >= 0;
      })
        const result = this._list.filter((x: any) => x.checked);
        this.control.setValue(
          result.map((x: any) => x[this.keys[1]]).join(",")
        );
        this.onChange(result.map((x: any) => x[this.keys[0]]));
    } else 
    {
      this.onChange(null);
        this.control.setValue(null);
    }
    this.stateChanges.next();
  }

And the methods

  ngOnDestroy() {
    this.stateChanges.complete();
    this._focusMonitor.stopMonitoring(this._elementRef);
  }

  setDescribedByIds(ids: string[]) {
    this.describedBy = ids.join(" ");
  }

  onContainerClick(event: MouseEvent) {
    if ((event.target as Element).tagName.toLowerCase() != "input") {
      this._elementRef.nativeElement.querySelector("input")!.focus();
    }
  }
  writeValue(value: any[] | null): void {
    this._value = value;
  }

  registerOnChange(fn: any): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }

  setDisabledState(isDisabled: boolean): void {
    this.disabled = isDisabled;
  }
0
votes

There is no default component in Angular Material which has both dropdown and filter built into single component. But there are three different ways to use drop down with filter.

  1. Angular Material autocomplete
  2. Create custom dropdown with filter by using mat-select and input as shown here

  3. Use third party components which provide the same functionality like mat-select-search

0
votes

Yes. You can use mat-select-filter from angular material