primeNG p-multiSelect 具有动态反应形式设置值

primeNG p-multiSelect with reactive form setting value dynamically

我正在尝试做一些简单的事情,以反应形式动态地为 p-multiSelect 设置一个值。 将 ngModel 与 p-multiSelect 属性 一起使用效果很好,但如果我将反应形式与 p-multiSelect 属性 一起使用,我无法从组件设置 p-multiSelect。

根据 angular 文档: "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

有一个 link 用于 stackblitz 重现:

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

分量:

  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);
  }

模板:

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

只传递选定值的数组而不是单个值

单值

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

多个值

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