p-autoComplete dataKey
If you have a PrimeNG PRO Support subscription please post your issue at;
https://pro.primefaces.org
where our team will respond within 4 business hours.
If you do not have a PrimeNG PRO Support subscription, fill-in the report below. Please note that your issue will be added to the waiting list of community issues and will be reviewed on a first-come first-serve basis, as a result, the support team is unable to guarantee a specific schedule on when it will be reviewed. Thank you for your understanding.
Current Waiting Time: ~8 weeks.
I'm submitting a ... (check one with "x")
[x ] bug report => Search github for a similar issue or PR before submitting
[ ] feature request => Please check if request is not on the roadmap already https://github.com/primefaces/primeng/wiki/Roadmap
[ ] support request => Please do not submit support request here, instead see http://forum.primefaces.org/viewforum.php?f=35
Plunkr Case (Bug Reports) Please demonstrate your case at stackblitz by using the issue template below. Issues without a test case have much less possibility to be reviewd in detail and assisted.
https://stackblitz.com/github/primefaces/primeng-issue-template
Current behavior
Expected behavior
Minimal reproduction of the problem with instructions
I'm using the p-autoComplete and I'm binding to an object.
ie. id label
dataKey="id" field="label" formControlName="customerId"
However, it's binding the result to the object whereas I am expecting it to set the customerId, instead it's setting customerId as the object vs. the id.
What is the motivation / use case for changing the behavior?
Please tell us about your environment:
- Angular version: 5.X
- PrimeNG version: 5.X
- Browser: [all | Chrome XX | Firefox XX | IE XX | Safari XX | Mobile Chrome XX | Android X.X Web Browser | iOS XX Safari | iOS XX UIWebView | iOS XX WKWebView ]
-
Language: [all | TypeScript X.X | ES6/7 | ES5]
-
Node (for AoT issues):
node --version=
You're misunderstanding a number of things.
field selects a property to show as label
dataKey is used to differentiate between multiple objects to improve performance in sorting / filterting
Neither of these fields decide what gets bound.
If you're binding to a list of {id: number, label: string}, but you want the id to bind to your customerId control, you have 2 options
a) Slightly refactor your code to follow PrimeNG's SelectItem class
Import from import { SelectItem } from "primeng/components/common/selectitem";
Then refactor your object to;
{
label: /* your customer label */,
value: /* your customer's id */
}
And use a list of the above to populate your p-dropdown
b) use (onChange) to set the properly correctly, using a dummy (for example) customerIdObject field to bind your object to, and then setting customerId in the (onChange)
Thanks - I did a workaround -but most bindings provide both a label and a value mapping.
Variant a) mentioned by @Mysame works with p-dropdown but not with p-autoComplete. AutoComplete does not work with SelectItem. See #4622.
I ended up creating an independent temporary form control to hold the whole object set by AutoComplete and hooking to onSelect and onClear events to set the true form control value:
<div [formGroup]="tmpGroup">
<p-autoComplete
[formControlName]="user"
(onSelect)="handleSelect($event)"
(onClear)="handleClear()"
...
></p-autoComplete>
</div>
tmpGroup = new FormGroup({ user: new FormControl() });
handleSelect(user) {
this.group.controls.userId.setValue(user.id);
}
handleClear() {
this.group.controls.userId.setValue(null);
}
@nikdo can you plz provide a live demo of your above running code.
@nikdo can you plz provide a live demo of your above running code.
Sorry, cannot do that, the app is not public. The code in my comment should work fine as it is.
Closing per discussion above.
field="label" will show rohit and koli in the dropdown list respectively and dataKey="id" will ensure (if rohit is selected) on submit of form will give anyFormControlName={label:"rohit",id:1}.
<p-autoComplete formControlName="anyFormControlName" [suggestions]="filteredresults" (completeMethod)="searchFromList($event)" field="label" dataKey="id" [dropdown]="true" (onDropdownClick)="showDropdown()">
export class labelid { label: string id: number }
dataset: labelid[ ] = [{label:"rohit",id:1},{label:"koli",id:2}];
filteredresults: labelid[ ] = [ ];
searchFromList(event) {
filteredresults= this.dataset
.filter(data => data.label.toString()
.toLowerCase()
.indexOf(event.query.toString().toLowerCase()) !== -1);
}
showDropdown() {
this.filteredresults;
}
while using field attribute ,formcontrol value is hiding,the input field is empty.
If you're binding both [formControl] (or formControlName) and (onSelect)="control.setValue(...)" you're going to end up with the value being patched twice which is bad.
I'm sharing my solution as a shared component for autocomplete:
<p-autoComplete [(ngModel)]="controlValue"
[class.ng-invalid]="control.invalid"
[suggestions]="filteredOptions"
(completeMethod)="search($event.query)"
(onBlur)="control.markAsTouched()"
[placeholder]="placeholder"
[forceSelection]="true"
field="name"
dataKey="id"
[attr.id]="id">
</p-autoComplete>
@Component({
selector: 'app-autocomplete',
templateUrl: './autocomplete.component.html',
styleUrls: ['./autocomplete.component.scss']
})
export class AutocompleteComponent implements OnInit {
@Input() id: string = uuidv4();
@Input() control: FormControl;
@Input() placeholder: string = 'Search';
@Input() options: SelectOption[];
@Output() valueChange: EventEmitter<any> = new EventEmitter();
@Output() valueSearch: EventEmitter<any> = new EventEmitter();
filteredOptions: SelectOption[];
set controlValue(value: SelectOption) {
this.control?.patchValue(value?.id);
this.valueChange.emit(value?.id);
}
get controlValue(): SelectOption {
return this.options?.find(opt => opt.id === this.control.value);
}
constructor() { }
ngOnInit(): void {
}
async search(searchTerm: any): Promise<void> {
this.filteredOptions = this.options.filter(opt => opt.name.toLowerCase().indexOf(searchTerm.toLowerCase()) === 0);
this.control?.markAsDirty();
this.valueSearch.emit(searchTerm);
}
}
basic usage without event bindings:
<app-autocomplete label="Street"
[options]="streets"
[control]="$any(group.get('streetid'))">
</app-autocomplete>
Notes:
SelectOptionin my case is just an interface withidandname. You may have any other type.- In my case,
optionsare pre-rendered so all I need to do is the filter them synchronously. if you're using a URL with query for the search I'd suggest to have a@Input() searchCallback: () => SelectOption[];to perform the search insidesearch().