[FIXED] p-multiSelect how prevent adding elements with the same index

Issue

I have a list of options for multi-select. in one of the option I should add another field-remark field. so selecting in the first time add this field. but when removing the selection it does not removing this selection from the array becouse I did not remove the remark field. so when select this option again will add twice the same index(one with the remark field and one with null in the remark) I need to set value only if I dont have this index in the array

<p-multiSelect [required]="formGroup.hasError('remark-reasons-required')"
                   [options]="reasons" defaultLabel="" formControlName="remarks"  optionLabel="hebName"         
                   selectedItemsLabel="{0} "
                   (onChange)="onChangeReasonsValue($event)"></p-multiSelect>

the same index added twice once with remark and one with null

 onChangeReasonsValue(event: { value: ReviewDecisionReasonModel[] }): void {
    //
    var selectedArray = event.value.filter(function (item, pos) {
      return event.value.indexOf(item) == pos;
    })
    this.formGroup.get('remarks').setValue(selectedArray);
    this.selectedReasons = selectedArray;
    this._decision.reasons = selectedArray;
}

Solution

It seems the multi-select component have a bug, where the disabled/removed options from the component remain added to the related formControl.

I propose you add a "disabled" property to your options, and set this option as the selections change instead of adding/removing them. After that, you could adjust the formValues with only enabled options.

Also, you could not use (OnChange) in favor of subscribing to the form changes from the component.

something like

otherReasonWhen2 = { id: 3, hebName: 'heb3', freeTextAllow: false, disabled: true };
  reasons = [
    { id: 1, hebName: 'heb1', freeTextAllow: false, disabled: false },
    { id: 2, hebName: 'heb2', freeTextAllow: false, disabled: false },
    this.otherReasonWhen2,
  ];

ngOnInit() {
    this.formGroup.get('remarks').valueChanges.subscribe((newValues) => {
      console.log(newValues) // This is here for you to see the values as they change
      this.otherReasonWhen2.disabled = newValues.every(reason => reason.id !== 2)

      if (newValues.some(reason => reason.disabled)){
        // work-around for the observed bug: when there are disabled options selected, remove them from the form.
        this.formGroup.get('remarks').setValue(newValues.filter(reason => !reason.disabled));
      }
    });
  }

and don’t forget to add the directive to disabled the option:

<p-multiSelect
    [options]="reasons"
    optionDisabled="disabled" <-- Here
    defaultLabel=""
    formControlName="remarks"
    optionLabel="hebName"
    selectedItemsLabel="{0} "
  ></p-multiSelect>

Answered By – The Fabio

Answer Checked By – Marilyn (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published