Issue
In an angular 12 (using typescript) application, there is a value object in a file "houseobject.ts" defined as:
export class houseValue {
houseCodeAndDesc: string;
numberBedrooms: number;
}
The JSON for houseValue comes across as: houseValue { houseCodeAndDesc: "10005 - Brownstone Apartment" numberBedrooms: "8" }
Unfortunately, the houseCodeAndDesc information needs to be broken up into the house code and house description (so houseCode: 10005, houseDesc: Brownstone Apartment).
I created a new value object as below in a file called houseobject2.ts:
export class houseValueBrokenUp{
houseCode: string;
houseDesc: string;
numberBedrooms: number;
}
I was trying to map the data from houseValue to houseValueBrokenUp as shown below:
export class houseTable {
@Input() houseSummary: houseValue[];
displayedColumns: string[] = ['houseCodeAndDesc', 'numberBedrooms'];
houseDisplayList: houseValueBrokenUp[];
houseDisplay: houseValueBrokenUp;
houseDataSource: MatTableDataSource<any>;
houseSplitDataSource: MatTableDataSource<houseDisplayList>;
@ViewChild(MatSort) sort: MatSort;
ngOnInIt() {
if(this.houseSummary) {
this.setInformation();
this.houseDataSource = new MatTableDataSource(this.houseSummary);
}
}
setInformation() {
for (const value of this.houseSummary) {
this.houseDisplay.houseCode = value.houseCodeAndDesc.substring(0,5);
this.houseDisplay.houseDesc = value.houseCodeAndDesc.substring(6);
this.houseDisplay.numberBedrooms = value.numberBedrooms;
this.houseDisplayList.push(this.houseDisplay);
}
}
}
The problem is when setInformation() runs, the browser's console gives an error of "Type Error: Cannot read properties of undefined (reading substring)". I believe it's saying that value in setInformation() is undefined, but when I console.log(value) the console shows the JSON information. What is the proper way to push the values from the original value object to the value object that splits the house code and description?
Solution
The reason is because houseDisplay
is not initialized and it's undefined
. So, you can initialize it like this:
houseDisplay: houseValueBrokenUp = {
houseCode: '',
houseDesc: '',
numberBedrooms: 0
};
Additionally, houseSummary
is undefined onInit
. Please read more the component lifecycle.
If you want to setup the information as soon as your content is available you can use getter and setter like this:
private _houseSummary: houseValue[];
houseDataSource = new MatTableDataSource([]);
get houseSummary():houseValue[]{
return this._houseSummary;
}
set houseSummary(houseSummary:houseValue[]){
this._houseSummary = houseSummary;
if(this._houseSummary) {
this.setInformation();
this.houseDataSource.data = this._houseSummary;
}
}
I'm not sure that's works because I've not tested directly but yeah... in case of errors... take a look at console and make a good error research online.
Answered By - Francesco Lisandro
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.