gpt4 book ai didi

angular - primeNG p-multiSelect 具有动态 react 形式设置值

转载 作者:行者123 更新时间:2023-12-03 14:32:55 25 4
gpt4 key购买 nike

我正在尝试做简单的事情,使用 react 形式动态地将值设置为 p-multiSelect。
使用带有 p-multiSelect 属性的 ngModel 效果很好,但是如果我使用带有 p-multiSelect 属性的 react 形式,我无法从组件设置 p-multiSelect。

根据 Angular 文档:
“在 Angular v6 中已弃用支持使用 ngModel 输入属性和 ngModelChange 事件与响应式(Reactive)表单指令,并将被删除”
https://angular.io/api/forms/FormControlName#use-with-ngmodel

stackblitz repro 有一个链接:

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

多重值(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 🚀🚀

关于angular - primeNG p-multiSelect 具有动态 react 形式设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57332904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com