본문 바로가기
TypeScript/Angular

Angular - tree구조 구현 및 표현

by le_piee 2020. 6. 5.

 

 

안녕하세요.

 

조직도 등을 구현을 하려고 할 때, 트리구조를 표현해야 하는 것들이 있습니다.

 

1

 ㄴ 1

      ㄴ1

      ㄴ2

  ㄴ 2

 

 

쉽게 설명하면 이런 구조입니다.

 

Angular에서는 라이브러리를 이용해서 쉽게 구현 할 수 있는데요.

 

한번 같이 해보겠습니다.

 

 

기본적으로 NPM과 Angular가 설치가 되어있어야 합니다.

 

제 버전은 이렇습니다.

 


 

 

1. 프로젝트 생성

 

ng new treeApp

 

 

2. 라이브러리 설치

npm install --save angular-tree-component

 

 

3. CSS 플러그인

@import '~angular-tree-component/dist/angular-tree-component.css';

/* styles.css에 붙혀넣으시면 됩니다 */

 

4. App.Module 작성

 

주석으로 표시해둔 곳을 작성해주시면 됩니다.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';   

import { TreeModule } from 'angular-tree-component';   //이곳

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    TreeModule.forRoot()   //이곳
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

 

 

5. Component.ts 작성

 

트리를 표현 할 배열을 만들어줍니다.

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

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


  nodes = [
    {
      id: 1,
      name: 'root1',
      children: [
        { id: 2, name: 'child1' },
        { id: 3, name: 'child2' }
      ]
    },
    {
      id: 4,
      name: 'root2',
      children: [
        { id: 5, name: 'child2.1' },
        {
          id: 6,
          name: 'child2.2',
          children: [
            { id: 7, name: 'subsub' }
          ]
        }
      ]
    }
  ];
  options = {};

  
}

 

 

6. App.component.html 작성

 

다 지우고 이것만 넣어줍니다.

<tree-root [nodes]="nodes" [options]="options"></tree-root>

 

 

 

7. 빌드 및 확인

ng serve

 

https://angular2-tree.readme.io/docs/getting-started

공식 사이트에 다양한 문서와 예제가 나와있습니다.

다음에는 drag & drop , 이벤트 감지 등 라이브러리 사용법에 대해 알아보겠습니다.