Crystal
Crystal

Reputation: 1505

How to preselect options within a multi or single mat-select that relies on an Input() value?

I have created this reusable select search component. This component can have preselected items. If the component is passed an array of preselected options then it should preselect them.

Currently, when I pass an item to preselect it correctly adds it to the form control, however it does not display correctly.

I have another Input() called extractValue where the user can pass the key value that should be displayed for the options.

I have tried compareWith function to pull the display value. This compareWith function runs BEFORE any Inputs() are fully loaded. So the extractValue is undefined. If I hard code this value it still doesn't seem to solve my issue.

Why does the form control set values not reflect in the UI?

Here is my code ---> https://stackblitz.com/edit/angular-mat-select-multi-with-formcontrol-klabfl?file=app/select-search-dropdown.component.html

Upvotes: 0

Views: 591

Answers (1)

wahab memon
wahab memon

Reputation: 2416

Found the cause of your compareWith function, it was not able to get the extractValue as the scope of this in your function was of mat-select and your actual value of extractValue was present in your this of main component.

I didn't find anything, which will allow us to pass the scope of your parent component. But as a workaround, you can do the following:

  1. Pass the extractValue in your selectSearchForm.
  2. Then, access it using: this._parentFormGroup.value.extractValue; and make changes accordingly in your compareFn.

Below are the code changes and working stackblitz

private _setUpFormControls(
    validators?: ISelectSearchValidators[],
    selected?: any,
    setInitialValue?: boolean,
    multiple?: boolean
  ): void {
    debugger;
    this.selectSearchForm = this._formBuilder.group({
      SelectControl: [
        this._setInitialValue(selected, setInitialValue, multiple),
        this._getValidatorFns(validators)
      ],
      SearchControl: [""],
      extractValue: this.extractValue
    }); 
  }

compareFn(optionOne: any, optionTwo: any): boolean {
    const extractValue = this._parentFormGroup.value.extractValue;
    if (typeof optionOne === "string" && typeof optionTwo === "string") {
      return optionOne === optionTwo;
    } else if (!!optionOne[extractValue] && !!optionTwo[extractValue]) {
      return optionOne[extractValue] === optionTwo[extractValue];
    }
  }

Upvotes: 1

Related Questions