When working with reactive forms, I encountered an issue understanding how data is mapped to form controls. Let's consider an object control with id and name properties, displayed as an input textbox where the user inputs the id. Utilizing autocomplete functionality retrieves the object data, such as:
{ id: 1234, description: "Some description" }
As this is an object and not a string, the input box displays [object Object] instead of the expected value format like 1234 - Some description
. To rectify this, I assume that implementing a toString
method for the object could help achieve the desired display format.
Below is a snippet of the form configuration:
this.orderForm = this.fb.group({
customer: '',
....
items: this.fb.array([ this.initItems() ])
...
The customer
and item
objects are similar in structure, whereby they both consist of id and description attributes.
export class Customer {
id: string;
descr: string;
toString = () => this.id + " - " + this.descr
}
export class ItemDetail {
id: string;
descr: string;
toString = () => this.id + " - " + this.descr
}
export class Order {
id: string;
...
customer: Customer;
items: Item[]
}
export class Item {
...
detail: ItemDetail
...
}
While loading order data into the form:
const itemsFGs = order.items.map(item => this.fb.group(item));
const itemsFA = this.fb.array(itemsFGs);
this.orderForm.setControl('items', itemsFA);
The challenge arises as the data is loaded as plain objects without being type casted to the appropriate classes, resulting in missing toString
method implementations for nested objects. Consequently, the input boxes display [object Object]
rather than utilizing the toString
method.
A typical JSON representation of an order might resemble:
{
id: "1",
customer: {
id: "1",
name: "some customer"
},
items: [{
detail: {
id: "1",
descr: "some item"
}
}]
}
The main concern shifts towards ensuring incoming JSON data is correctly captured within respective classes, allowing methods like toString
to be accessible for proper display purposes.