Home > Blockchain >  Angular interfaces -- inserting object to a nested array ( Cannot read properties of undefined)
Angular interfaces -- inserting object to a nested array ( Cannot read properties of undefined)

Time:08-29

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
}

CodePudding user response:

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'
    }) ;
  }

CodePudding user response:

The issue is that you are trying to push an item to an array position/index that doesn't exist, hence the error. the variable templates which is an array is of length 0. In order to be able to do what you want to do, the variable templates must have values.

  • Related