angular - PrimeNG patchValue for autocomplete
问题描述
I am trying to assign a value dynamically to auto-complete but it is not working
HTML
<label for="centerId" class="control-label">Center</label>
<p-autoComplete formControlName="center" id="centerId" [suggestions]="iCenter" placeholder="Center (required)" (completeMethod)="searchCC($event)" [style]="{'width':'85%'}" [inputStyle]="{'width':'85%'}" field="name" dataKey="id" [dropdown]="true"></p-autoComplete>
interface
export interface ICenter{
id: string,
name: string
}
ts
(for field="name" dataKey="id" the value is the same, so id=name)
iCenter: ICenter[];
also confirmed there is a value
console.log(this.center)
searchCC(event) {
this.iCenter = this.iCenter
.filter(data => data.name.toString()
.toLowerCase()
.indexOf(event.query.toString().toLowerCase()) !== -1);
}
this.ersaForm = this._fb.group({
center: ['', Validators.required],
});
this.ersaForm.patchValue({
//also tried center:center
//also tried center: [itimData.center, itimData.center],
center: [{ 'field': this.center,'dataKey': this.center}],
phone: itimData.phone,
email: itimData.email
});
***************************************UPDATE***************************************************************** Got it working , here is how
center: {id: itimData.center, name: itimData.center },
解决方案
The properties 'field' and 'dataKey' are not necessarily part of your object.
PrimeNG docs:
field
Field of a suggested object to resolve and display.
dataKey
A property to uniquely identify a value in options.
If your list looks like this:
const items = [
{id: 1, name: 'Apple'},
{id: 2, name: 'Banana'},
{id: 3, name: 'Pineapple'}
];
Then the property 'field' should refer to 'name' and 'dataKey' to 'id'.
Now if you want to set the value of the autocomplete to 'Pineapple' then patchValue looks like this.
this.form.patchValue({
item: {
id: 3, // mandatory
name: 'Pineapple' // optional
}
});
The PrimeNG component will search for an object with the id equal to 3. When there is a match he will set the selection to that object.
推荐阅读
- html - 如何在 Woocommerce 的 div 中添加父类?
- amazon-web-services - AWS API Gateway,带有 CDK 的默认基本映射
- database - PostgreSQL - 连接到新数据库非常慢
- c# - C#如何从变量中获取最大和最小数值(两者)
- ios - Kotlin Multiplatform - 错误 ITMS-90171:无效的捆绑包结构
- python - Matplotlib 问题:为什么颜色条会删除我的 xlabel?我该如何避免呢?
- sql-server - 在一个触发器中插入、更新
- sql - 使用 2 个表创建触发器
- ansible - Ansible:如何将受任务影响的所有主机存储在变量中?
- cypress - 赛普拉斯全局 cy.fixture 设置