Issue
I have an Angular Model and I am trying to push it to an array to create repeater fields. The array is then iterated to create html fields in a component. However, while pushing to the array, an undefined error is thrown .
Here is the Model code:
export class TierModel {
feeName: string;
feeDescription: string;
unit: string;
tierStart: number;
tierEnd: number;
rate: number;
};
And here is the code that pushes Model to array:
addForm()
{
const obj = new TierModel()
obj[0].feeName = 'test';
obj[0].unit = 0;
this.dataarray.push(obj);
}
The aim is to use an index with the object and then push it to the array so that any modification is to be done before pushing it to the array would be done here using index.
Any help would be more than
Solution
This is all messed up,
There is no obj[0]
, obj
is not an array, its an instance of class, that has no constructor.
And pay attention to types, you are defining unit
as string
but giving it value of number
.
Additionally, you dont even need to export class for this. Creating something with new <class>()
is confusing when in reality its just an object. If you are declaring object you need to see {}
, this is how you make it understandable for anyone on the first look.
This is how you do what you are trying to do
export interface TierModel {
feeName: string;
feeDescription: string;
unit: number;
tierStart: number;
tierEnd: number;
rate: number;
}
export class AppComponent implements OnInit {
objArray: TierModel[] = [];
constructor() {}
ngOnInit(): void {
this.addForm();
console.log(this.objArray);
}
addForm() {
let obj = <TierModel>{};
obj.feeName = 'aaa';
obj.unit = 1;
this.objArray.push(obj);
}
}
Answered By - tony
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.