This drives me mad.
So, value is string value of 1.
Options:
Code: Select all
[{ "id": 1, "description": "item1" }, { "id": 2, "description": "item2" }]
Set the dataKey to "id", ngModel is a value of "1"...
Then this comes along and makes me want to burn a book.
objectutils.ts
Code: Select all
public resolveFieldData(data: any, field: any): any {
if(data && field) {
if (this.isFunction(field)) {
return field(data);
}
else if(field.indexOf('.') == -1) {
return data[field];
}
else {
let fields: string[] = field.split('.');
let value = data;
for(let i = 0, len = fields.length; i < len; ++i) {
if (value == null) {
return null;
}
value = value[fields[i]];
}
return value;
}
}
else {
return null;
}
}
Issue is that now in the first pass, data is "1" with a field of "id" BUT when it passes the next check to see if the selectedItem should be set when calling;
dropdown.ts
Code: Select all
findOptionIndex(val: any, opts: any[]): number {
let index: number = -1;
if(opts) {
for(let i = 0; i < opts.length; i++) {
if((val == null && opts[i].value == null) || this.objectUtils.equals(val, opts[i].value, this.dataKey)) {
index = i;
break;
}
}
}
return index;
}
Issue.... val = "1", opts[0].value = { "id": 1, "description": "item1" }, dataKey = "id"
can you see who this WILL NOT equal and fail every damn time?! So, I set val to be { "id": 1 } cause that should mean data[field] should return 1... BUT NO I need the full object of { "id": 1, "description": "item1" } (MAKES COMPLETE SENSE DO NOT GET ME WRONG, BUT, BUT, I will not store that object JUST THE VALUE OF ID!) but by GOD 4 hours of my life wasted.
This is way over complicated to understand yourself when you want to use dataKey when you cannot re-write your entire backend to use label and value items in lists.
So, because there is NOTHING to help with understanding the dataKey, here it is.
If using dataKey set this to be the key value of which you are storing, i.e. if you have { "id": 1 } then set the dataKey to be "id".
Now, the ngModel connection or even formControl must match the item in the list, so if you have options like above in the first code block the selected item must match this, so if you only get the id from the database you will have to filter your list to a selected item and THEN make sure you flip this back when talking to the server.
Code: Select all
items: List[] = [];
selectedItem: List = new List();
selectedValue = '2';
someSetListFunc() {
someHttpGetProcess().sub(response => {
this.items = response.data;
this.selectedItem = this.items.filter(x => x.id === this.selectedValue)[0];
});
}
someSendToServer() {
myServerObject: Server = new Server();
myServerObject.someId = this.selectedItem.id;
}
// <p-dropdown [options]="items" [(ngModel)]="selectedItem" dataKey="id" optionalLabel="description"></p-dropdown>
So, when you adding this to the docs?! Can you understand why I'm unhappy about this?! Had to debug to understand the code, because! there is nothing to say how this works.