I am have a class as follows:
export class Template {
public Id: Number;
public FileName: string;
}
The following snippet is from a function where I want to first create an object (of type Template
) and push it to the array. The code breaks at temp.Id
with error:
ERROR TypeError: Cannot set property 'Id' of undefined.
The template is initially empty. templates
is an array that contains some file names. Array declared as: templateObjects: Template[] = new Array();
for (let i = 0; i < this.templates.length; i++) {
var temp: Template;
temp.Id = i;
temp.FileName = this.templates[i].toString();
this.templateObjects.push(temp);
}
u are not newing up Template
let temp is just declaring variable but new initialize it(allocate memory) then u will be able to assign other properties to it
for (let i = 0; i < this.templates.length; i++) {
let temp = new Template() ;
temp.Id = i;
temp.FileName = this.templates[i].toString();
this.templateObjects.push(temp);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.