Can the component itself be imported into the template?

2

I need to arm in Angular.io a kind of tree specifically an Organigram where the different areas are defined, for that my question is if you can define a component that calls itself within itself so that it iteratively draws the tree something like this:

nodo.component.ts

@Component({
    selector: 'nodo'
    templateUrl: 'nodo.html'
})
export class NodoComponent {
    @Input() nombre: string;
    @Input() hijos: any[];
}

node.html

<div>
    <label>{{ nombre }}</label>   
    <!-- esta parte nose si se puede hacer -->
    <nodo 
        *ngFor="let nodo of hijos"
        [nombre]="nodo.nombre" 
        [hijos]="nodo.hijos">
    </nodo>
</div>

It is possible this type of behavior in Angular2 or how to proceed in these cases to be able to draw the tree, by the way I was looking at the available components and none of them seems sufficient for my particle problem although in this question it is only reduced to this.

    
asked by Ricardo D. Quiroga 26.09.2017 в 17:00
source

1 answer

2

It is possible to do what you say, although with a small change.

DEMO STACKBLITZ

I guess the structure you have to go through is something like this:

  [
    {
      nombre : 'Wisconsin',
      hijos : [
        { 
          nombre : 'Meteora', 
          hijos : [{ 
            nombre : 'Arkansas',
            hijos : [
              {nombre : 'Jose', hijos : [{
                nombre : 'Hermosilla',
                hijos : [{
                  nombre : 'Rodrigo'
                }]
              }]}
            ]
          }]
        }
      ]
    }
  ]

Your Nodo component should go through that list and create new Nodos if the hijos property exists in an item in the list.

import { Component, Input } from '@angular/core';

@Component({
  selector: 'node',
  template: '
    <div *ngFor="let element of elements">
      <p>{{element.nombre}}</p>
      <node 
        *ngIf="element.hijos && element.hijos.length"
        [elements]="element.hijos"
      ></node>
    </div>
  '
})
export class NodeComponent  {
  @Input() elements : any[];
}
    
answered by 26.09.2017 / 17:50
source