I want to push object to subCategory which is an array under ITemplate interface but I am receiving error TypeError: Cannot read properties of undefined (reading 'subCategory')
.
How do i push an object to subCategory array?
Any idea guys how to make this possible and what causes the error ?
Thanks, appreciated.
#ts code
import { Component, OnInit } from '@angular/core'
interface ITemplate {
id: number;
entitlement: string;
required: boolean;
isHeaderCategory: boolean;
subCategory: ITemplate2[]
}
interface ITemplate2 {
id: number;
sub_name: string;
}
const mockData: ITemplate[] = []
@Component({
selector: 'app-template',
templateUrl: './template.component.html',
styleUrls: ['./template.component.css'],
})
export class TemplateComponent implements OnInit {
constructor() {}
ngOnInit(): void {
console.log('thiss' , this.templates)
}
add() {
this.templates[0].subCategory.push({
id: 0,
sub_name: 'test'
})
}
templates: ITemplate[] = mockData
}
You're trying to access this.templates
0th
element and inside that element you are trying to push into subCategory, but first you should have 0th element in first place for this.templates
.
try this.
add() {
this.templates.push({
id:1,
entitlement: 'string related to entitlement',
required: true;
isHeaderCategory: false;
subCategory: []
});
this.templates[0].subCategory.push({
id: 0,
sub_name: 'test'
}) ;
}