firasKoubaa firasKoubaa - 3 years ago 197
TypeScript Question

Angular Typescript : Using an Object as an attribute of another Object before its definition

i'm implementing "parents-childs" relations between several objects derived from the same class.

My class (model) is the following :

export class Node {
public name: string;
public isLocked: boolean;
public canBeUnlocked: boolean;
public parentNodes: Node[];
public childNodes: Node[];

Under my component i'm declaring several objects derived from this model , but some objects are using objects before their plain declaration:


import { Component, OnInit } from '@angular/core';
import {Node} from '../models/node.model';

selector: 'app-mage',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
export class TestComponent implements OnInit {
NodesList= [];
Node1: any;
Node2: any;
Node3: any;
Node4: any;
Node5: any;
Node6: any;

constructor() {
this.Node1 = new Node('Node1', false, true , null, [this.Node2]);
this.Node2 = new Node('Node2', true, true, [this.Node1], [this.Node3 , this.Node4]);
this.Node3 = new Node('Node3', true, false , [this.Node2], [this.Node5]);
this.Node4 = new Node('Node4', true, false , [this.Node2], [this.Node6]);
this.Node5 = new Node('Node5', true, false , [this.Node3], null);
this.Node6 = new Node('Node6', true, false , [this.Node4], null);
// The list
this.NodesList = [this.Node1, this.Node2, this.Node3 , this.Node4 , this.Node5 , this.Node6];

ngOnInit() {

The problem , is with the "child nodes" ,

for example for the Node1 : Node2 is a child node , but it's get "undefined" when calling
, maybe because i'm calling Node2 as an attribute for the Node1 , before defining Node2 itself .

THe problem is occuring similarly with the other nodes.

Any idea to deal with that ??
Suggestions ??

Answer Source

It is just undefined, impossible to console.log value of undefined object. Solution depends on your goals.

For example, you can:

  public parentNodes?: Node[];
  public childNodes?: Node[];

This will allow create object without child nodes, so console.log will output your objet, just without some properties that hasn't been initialed.


<div> {{ Node2.childNodes?[0] }}  </div>

this will show first childNode in HTML if node has it.

You could also add missing childNodes in some other Angular's lifeCycleHook:

ngOnInit() {
  this.Node2.childNodes = [this.Node1, this.Node3];

ngAfterViewInit() {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download