2

I have object somethig like this:

{
 id: 1,
 text: "Main",
 childText: [
   {
    id: 3,
    text: "Child 1",
    childText: [
      {
        id: 5,
        text: "child 2"
        childText: [
        ....
        ]
      }
    ]
   }
 ]    
}

Any object can have childText any idea how to display this?

1

1 Answer 1

5

You should use a self-referencing component to do that:

@Component({
  selector: 'app-tree-view',
  templateUrl: './tree-view.component.html',
  styleUrls: ['./tree-view.component.css']
})
export class TreeViewComponent implements OnInit {
    @Input() data: {children: Array<any>,name: string,id: number};
    showChildren: boolean;
}

In tree-view.component.html:

<ul class="office-list-unstyled" *ngIf="data">
  <li [ngClass]="{'office-parent': d.children.length && !showChildren,'office-child': d.children.length && showChildren}"
  *ngFor="let d of data.children">
    <span (click)="toggleOffices(d)">{{d.name}}</span>
    <app-tree-view *ngIf="d.children.length && showChildren" [data]="d"></app-tree-view>
  </li>
</ul>

Note that, *ngIf in the view is the thing to stop the loop. And then you can use it in another component:

<app-tree-view [data]="offices"></app-tree-view>

Offices is your initial data for example.

Sign up to request clarification or add additional context in comments.

3 Comments

What is inside tree-view.component.html ?
@VladimirDjukic Look at In the Html part of my answer.
How then I call that component from other component?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.