본문 바로가기
TypeScript/Angular

angular - tree(2) 이동 및 이벤트 감지

by le_piee 2020. 6. 7.

안녕하세요. 

 

저번시간에 angular-tree-component를 이용해서 트리구조를 표현하는 것을 알아봤는데요.

 

이번시간에는 Drog&Drop 기능을 넣어서 트리구조 변경을하고, 그 변경을 감지하여 값을 가져오는 것을 해보겠습니다.

 

 

 

1.HTML 작성

<tree-root [nodes]="nodes" [options]="options" [focused]="true" (moveNode)="onMoveNode($event)" ></tree-root>

(moveNode)가 노드 이동을 감지하며, 트리의 노드가 변경이 되면, 연결되어있는 함수를 실행 시킴과 동시에 이벤트를 같이 전송합니다.

 

 

2. component.ts 파일 작성

import { Component } from '@angular/core';
import { ITreeState, ITreeOptions} from 'angular-tree-component';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'treeApp';


  nodes = [
    {
      id: 1,
      name: '엄마',
      children: [
        { id: 2, name: 'child1' },
        { id: 3, name: 'child2' }
      ]
    },
    {
      id: 4,
      name: '아빠',
      children: [
        { id: 5, name: 'child2.1' },
        {
          id: 6,
          name: 'child2.2',
          children: [
            { id: 7, name: 'subsub' }
          ]
        }
      ]
    }
  ];

	//트리 이동 
  state: ITreeState = {
    expandedNodeIds: {
      1: true,
      2: true
    },
    hiddenNodeIds: {},
    activeNodeIds: {}
  };
  options: ITreeOptions = {
    allowDrag: (node) => node.isLeaf,
    getNodeClone: (node) => ({
      ...node.data,
      //id: v4(),
      name: `copy of ${node.data.name}`
    })
  };

	//이벤트 감지 함수
  onMoveNode($event){
    console.log('Moved ->' + JSON.stringify( $event.node));
    console.log('to ->' + JSON.stringify( $event.to.parent));
    console.log('at index->' + JSON.stringify( $event.to.index));
    
  }
  
  

}

 

 

 

 

3. 확인 

 

이러한 이벤트를 통해 

이동한 노트의 값, 이동한 노드의 부모 값 등을 가져 올 수 있습니다.