[FIXED] primeNG p-multiSelect with reactive form setting value dynamically

Issue

I am trying to do simple thing dynamically set a value to p-multiSelect with a reactive form.
Using the ngModel with p-multiSelect property works nice but if I use the reactive form with the p-multiSelect property i can’t set p-multiSelect from component.

According angular doc:
“Support for using the ngModel input property and ngModelChange event with reactive form directives has been deprecated in Angular v6 and will be removed ”
https://angular.io/api/forms/FormControlName#use-with-ngmodel

There is a link for stackblitz repro:

https://stackblitz.com/edit/multyselectandform?file=src/app/app.component.ts

component:

  groupForm: FormGroup;
  cities: SelectItem[] = [
    { label: 'New York', value: 1 },
    { label: 'Rome', value: 2 },
    { label: 'London', value: 3 },
    { label: 'Istanbul', value: 4 },
    { label: 'Paris', value: 5 }
  ];
  setected = { label: 'Istanbul', value: 4 };

  constructor(private fb: FormBuilder) {
    this.groupForm = this.fb.group({
      selectedCities: ["", Validators.nullValidator],
    });
    //************doesn't work*************
    this.groupForm.get('selectedCities').setValue(this.setected);
    // this.groupForm.get('selectedCities').setValue(4);
  }

template:

 <div class="form-group">
       <label for="cities" class="control-label">Cities</label>
        <p-multiSelect [options]="cities" formControlName="selectedCities"></p-multiSelect>
 </div>

Solution

just pass an array of selected value not a single value

single value

this.groupForm.get('selectedCities').setValue([4]);

multiple value

this.groupForm.get('selectedCities').setValue([4,5]);  

and the mention this in the documentation page
MultiSelect detects changes to options and selected values using
setters so when changing your model, prefer creating a new array
reference instead of manipulating an existing array.

demo 🚀🚀

Answered By – Muhammed Albarmavi

Answer Checked By – Senaida (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published