Пользовательский компонент дерева Angular5 - PullRequest
0 голосов
/ 28 августа 2018

Как создать пользовательский компонент дерева в angular 5. Я новичок в angular. Понятия не имею.

enter image description here

«+» Кнопка создания нового узла и кнопка «Добавить маршрут» для создания подузла. Каждый узел содержит два раскрывающихся списка для выбора значений.

1 Ответ

0 голосов
/ 28 августа 2018

В основном вам нужно рекурсивно вызвать компонент. Вот простой пример:

node.model.ts

export class Node {
  children: Node[];
  text: string;
}

tree.component.ts

@Component({
  selector: 'tree',
  template: `<h1>Tree component</h1>
        <div *ngFor="let node of tree">
         <node [node]="node"></node>
        </div>
        <button (click)="addNodeTo()">add node</button>


  `,
  styles: [`h1 { font-family: Lato; }`]
})
export class TreeComponent implements OnInit {
  tree: Node[] = [];
  ngOnInit(){
    let firstNode = {
      children: [],
      text: 'first'
    }
    this.tree.push(firstNode);
  }

  addNodeTo(){
      let newNode = {
        children: [],
        text: 'newNode',
      }
      this.tree.push(newNode);
  }

и node.component.ts , который вызывается рекурсивно:

@Component({
  selector: 'node',
  template: `
    {{node.text}} <button (click)="addChildren(node)">Add children</button>
    <div *ngFor="let children of node.children">
      <node [node]='children'></node>
    </div>

  `,
  styles: [`h1 { font-family: Lato; }`]
})
export class NodeComponent implements OnInit {
  @Input() node: Node;
  ngOnInit(){
  }

  addChildren(node: Node){
      let newNode = {
        children: [],
        text: node.text +  `'s child`
      }
      node.children.push(newNode);
  }

Вот stackblitz без стилей, но вы поймете логику.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...