primeNG p-multiSelect with reactive form setting value dynamically

情到浓时终转凉″ 提交于 2020-08-27 21:42:28

问题


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>

回答1:


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 🚀🚀



来源:https://stackoverflow.com/questions/57332904/primeng-p-multiselect-with-reactive-form-setting-value-dynamically

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!