[FIXED] create a 2nd layer nested object to update data in angular


Thanks for your help.

P/G: Angular 14 with Typescript

I’d like to create a nested Object with a loop. So, I can generate a Mat-Tree in angular later. This photo comes from Angular’s offical mat-tree example.

Ultimately, I’d like to create something like this and fully customize every name of parent’s node and child node.
enter image description here

  1. I want to create a variable with interface which represent like below.
    for example:
    export interface CellLeaderTree{
      name: string;
      child: CellMemberTree;
    export interface CellMemberTree {
      childName: string;
      hasChild: boolean;

I have tried like this:

    const obj1 = {} as CellLeaderTree;
      obj1.name = 'Young';    // this works.
      // obj1.child = "me";      // this does not work.
      // obj1.child.hasChild = true;    // this does not work.
      // obj1.child.childName = "test";    // this does not work.
      //obj1.child.childName = "Mike";       // this does not work.
      //  obj1.child.hasChild = true;    // this does not work.

Could you help me to create a object variable with nested with children?

  1. In the above Tree, I want to update every name of the tree.
    for example, I want to change "Groceries".
    Also, I want to change all of Groceries’ children.
    Also, I want to able to change "Fruits" and its children.

In order to do like above, how should i structure my interface and create object in typescripts?

** Input Data as a replacement of Top Tree node name such as Groceries :

["Mike", "David","Vic"];

** first layer of children such as "Amond Meal flour"… or Fruits":

["child1", "child2", "child3"]

** 2nd layer of children such as "Apple":

["grand-child1", "grand-child2"]

— error message:
Cannot set properties of undefined (setting ‘childName’)

Thanks again,


you should create two interfaces:

export interface CellLeaderTree {
    name: string; // the name of the cell 
    children: CellMiddleTree[];

 export interface CellMiddleTree {
    name: string;
    children: string []; // this can contain only simple children

then simply:

obj1: CellLeaderTree = { name: 'Young', children: [
   {name: 'child', children: ['grand child 1', 'grand child 1']

Answered By – Eli Porush

Answer Checked By – Clifford M. (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published