Issue
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
}
Solution
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'
}) ;
}
Answered By - Prashant Singh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.