Angular 탐색 서랍 구성 요소 개요

    Ignite UI for Angular는 측면 탐색 컨테이너입니다. 콘텐츠 위에 놓일 수 있고 보기에서 슬라이드 인/아웃하거나 콘텐츠 내에서 확장/축소되도록 고정할 수 있습니다. 미니 버전은 닫혀 있어도 탐색에 빠르게 액세스할 수 있습니다. Navigation Drawer는 반응형 모드 선택 및 터치 제스처를 제공합니다. 콘텐츠는 완전히 사용자 정의할 수 있으며 기본 메뉴 항목 스타일을 사용할 수 있습니다.

    Angular 탐색 서랍 예제

    Ignite UI for Angular 시작하기

    Ignite UI for Angular Navigation Drawer 구성 요소를 시작하려면 먼저 Ignite UI for Angular 설치해야 합니다. 기존 Angular 애플리케이션에서 다음 명령을 입력합니다.

    ng add igniteui-angular
    

    Ignite UI for Angular에 대한 전체 소개는 시작 항목을 참조하십시오.

    첫 번째 단계는 다음 파일을 가져오는 것입니다.IgxNavigationDrawerModule 우리 안에서 app.module.ts 파일.

    메모

    IgxNavigationDrawerComponent 또한 다음 조건에 따라 다릅니다.BrowserAnimationsModule 그리고 필요HammerModule 터치 상호작용을 위한 것이므로 AppModule에도 추가되어야 합니다:

    // app.module.ts
    ...
    import { HammerModule } from '@angular/platform-browser';
    import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
    import { IgxNavigationDrawerModule } from 'igniteui-angular/navigation-drawer';
    // import { IgxNavigationDrawerModule } from '@infragistics/igniteui-angular'; for licensed package
    
    @NgModule({
        ...
        imports: [..., BrowserAnimationsModule, HammerModule, IgxNavigationDrawerModule],
        ...
    })
    export class AppModule {}
    

    또는16.0.0 독립 실행형 의존성으로 가져오IgxNavigationDrawerComponent 거나, 토큰을IGX_NAVIGATION_DRAWER_DIRECTIVES 사용해 컴포넌트와 그 지원 컴포넌트, 명령어를 가져올 수도 있습니다.

    // home.component.ts
    
    import { HammerModule } from '@angular/platform-browser';
    import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
    import { NgFor } from '@angular/common';
    import { IGX_NAVIGATION_DRAWER_DIRECTIVES } from 'igniteui-angular/navigation-drawer';
    import { IgxRippleDirective } from 'igniteui-angular/directives';
    import { IgxIconComponent } from 'igniteui-angular/icon';
    // import { IGX_NAVIGATION_DRAWER_DIRECTIVES, IgxRippleDirective, IgxIconComponent } from '@infragistics/igniteui-angular'; for licensed package
    
    @Component({
      selector: 'app-home',
      template: `
        <div class="content-wrap">
          <igx-nav-drawer [isOpen]="true">
            <ng-template igxDrawer>
              <nav>
                <span igxDrawerItem [isHeader]="true">Components</span>
                <span
                  *ngFor="let item of navItems"
                  igxDrawerItem
                  [active]="item.text === selected"
                  igxRipple
                  (click)="navigate(item)"
                >
                  <igx-icon fontSet="material">{{ item.name }}</igx-icon>
                  <span>{{ item.text }}</span>
                </span>
              </nav>
            </ng-template>
          </igx-nav-drawer>
          <main>
            <!-- app content -->
          </main>
        </div>
      `,
      styleUrls: ['home.component.scss'],
      standalone: true,
      imports: [BrowserAnimationsModule, HammerModule, IGX_NAVIGATION_DRAWER_DIRECTIVES, IgxRippleDirective, IgxIconComponent, NgFor],
      /* or imports: [BrowserAnimationsModule, HammerModule, IgxNavigationDrawerComponent, IgxNavDrawerTemplateDirective, IgxNavDrawerItemDirective, IgxIconComponent, IgxRippleDirective, NgFor] */
    })
    export class HomeComponent {
      public navItems: Product[];
    }
    

    이제 Ignite UI for Angular Navigation Drawer 모듈이나 지시어를 가져왔으니, 컴포넌트igx-nav-drawer 사용을 시작할 수 있습니다.

    Angular Navigation Drawer 사용

    종속성을 가져오면 탐색 창을 앱 구성 요소 템플릿에 정의할 수 있습니다.

    <igx-nav-drawer id="navdrawer" [isOpen]="true">
      <!-- template(s) -->
    </igx-nav-drawer>
    

    서랍의 내용은 지시로 장식<ng-template> 되어 제공되어야igxDrawer 합니다. 템플릿 내에서 어떤 콘텐츠든 제공할 수 있지만,igxDrawerItem 아이템 스타일링 지침(항목 스타일링)은 아이템에 기본 스타일링을 적용할 수 있습니다. 이 지침은 두 가지@Input 속성을 가집니다:

    • active선택한 항목에 스타일을 맞추는 것.
    • isHeader항목을 그룹 헤더로 스타일링하려면 활성화될 수 없습니다.

    이 지침은igxRipple 전체적인 분위기를 완성합니다:

    <!-- app.component.html -->
    <div class="content-wrap">
      <igx-nav-drawer id="navigation" #drawer [isOpen]="true">
        <ng-template igxDrawer>
          <nav>
            <span igxDrawerItem [isHeader]="true">Components</span>
            <span *ngFor="let item of navItems" igxDrawerItem [active]="item.text === selected" igxRipple (click)="navigate(item)">
              <igx-icon fontSet="material">{{ item.name }}</igx-icon>
              <span>{{ item.text }}</span>
            </span>
          </nav>
        </ng-template>
      </igx-nav-drawer>
      <main>
        <!-- app content -->
      </main>
    </div>
    

    추가 템플릿은 다음과 같이 장식되어 있습니다.igxDrawerMini 대안에 대한 지침이 제공될 수 있습니다 미니 변형 폐쇄된 상태로.

    메모

    탐색 창은 콘텐츠 위에 떠 있거나 콘텐츠 옆에 고정될 수 있습니다. 기본적으로 서랍은 뷰포트 크기에 따라 해당 모드 간에 전환됩니다. 자세한 내용은 모드를 참조하세요.

    서랍 전환 모드를 수용하기 위해 두 콘텐츠 섹션 주위의 간단하고 유연한 래퍼 스타일을 다음과 같이 지정할 수 있습니다.

    /* app.component.css */
    .content-wrap {
      width: 100%;
      height: 100%;
      display: flex;
    }
    

    탐색 창에 요소를 추가하고 이를 선택할 수 있으려면 TypeScript 파일이 다음과 같아야 합니다.

    /* app.component.ts */
    @Component({...})
    export class AppComponent {
        public navItems = [
            { name: 'account_circle', text: 'Avatar' },
            ...
        ];
    
        public selected = 'Avatar';
    
        public navigate(item) {
            this.selected = item.text;
        }
    }
    

    서랍을 열고 닫는 방법은 여러 가지가 있습니다. 입력 속성은 앱 상태에 바인딩할 수 있으며, 구성 요소 내 API에 대한 프로그래밍 접근을 통해 다음을 사용할 수 있습니다.@ViewChild(IgxNavigationDrawerComponent) 참조 또는 이 경우에는#drawer 템플릿 참조 변수:

    <button (click)="drawer.toggle()">Menu</button>
    

    내비게이션 서랍은 또한 ID와 통합igxNavigationService 되어 지시를 통해igxToggleAction 타겟팅할 수 있습니다.

    다음으로 교체해 봅시다.<main> 안으로 app.component.html 다음에 추가하여igxIconButton 그리고 아이콘 구성 요소 토글 스타일링:

    <main>
      <span igxIconButton="flat" igxToggleAction="navigation">
        <igx-icon fontSet="material">menu</igx-icon>
      </span>
    </main>
    

    또한, 서랍에서 아이템을 선택할 때 서랍이 닫히길 원한다면, 다음과 같은 참조를@ViewChild(IgxNavigationDrawerComponent) 사용할 수 있습니다:

    /* app.component.ts */
    import { Component, ViewChild } from '@angular/core';
    import { IgxNavigationDrawerComponent } from 'igniteui-angular/navigation-drawer';
    // import { IgxNavigationDrawerComponent } from '@infragistics/igniteui-angular'; for licensed package
    
    @Component({...})
    export class AppComponent  {
        @ViewChild(IgxNavigationDrawerComponent, { static: true })
        public drawer: IgxNavigationDrawerComponent;
    
        // And of course add the key line to our navigate function
    
        public navigate(item) {
            this.selected = item.text;
            this.drawer.close();
        }
    }
    

    모든 것이 순조롭게 진행되었다면 브라우저에 데모 샘플이 표시될 것입니다.

    모드

    고정 해제(콘텐츠 위로 올라감) 모드는 서랍이 위에 위치하여 콘텐츠 위에 어두운 오버레이를 적용하는 일반적인 동작입니다. 일반적으로 모바일 장치에 적합한 임시 탐색을 제공하는 데 사용됩니다.

    서랍을 고정하여 더 큰 화면을 활용하고 상대적인 위치에 따라 정상적인 콘텐츠 흐름 내에 배치할 수 있습니다. 앱이 서랍을 전환하는 방법을 제공하는지 여부에 따라 고정 모드를 사용하여 영구적 또는 지속적인 동작을 달성할 수 있습니다.

    메모

    기본적으로 내비게이션 서랍은 반응형으로, 화면 크기에 따라 고정 해제 모드와 고정 모드 사이를 적극적으로 전환합니다. 이 동작은 속성에 의해pinThreshold 제어되며, 가짜 값(예: 0)을 설정하여 비활성화할 수 있습니다.

    고정된(영구) 설정

    핀은 서랍fixedrelative의 위치를 내용물과 같은 흐름에 올리도록 변경합니다. 따라서 앱 스타일링은 이러한 레이아웃을 고려해야 하며, 특히 이 모드에서 서랍을 토글해야 할 경우에는 더욱 그렇습니다. 이처럼 유연한 레이아웃을 구현하는 방법은 여러 가지가 있지만(프로그래밍 방식도 포함), 가장 쉬운 방법은 지시문(directivesigxLayout)을 사용하는igxFlex 것입니다.

    이전 예에 적용된 모습은 다음과 같습니다.

    <div class="content-wrap" igxLayout igxLayoutDir="row">
      <igx-nav-drawer id="navigation" #drawer [isOpen]="true" [pin]="true" [pinThreshold]="0">
        <!-- template(s) -->
      </igx-nav-drawer>
      <main igxFlex>
        <!-- content here -->
      </main>
    </div>
    
    .content-wrap {
      width: 100%;
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
    }
    

    이제 변경된 예는 다음과 같아야 합니다.

    서랍은 호스트 요소에 적용flex-basis 되어 나머지 내용이 나머지 너비를 차지할 수 있게 합니다. 또는 지시를 사용해 건너뛰는 수동 스타일링은 다음과 유사하게 적용할 수 있습니다:

    .main {
      position: absolute;
      display: flex;
      flex-flow: row nowrap;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      width: 100%;
    }
    
    .main > * {
      width: 100%;
    }
    

    미니 변형

    미니 버전에서는 내비게이션 드로어가 닫히지 않고 폭이 변경됩니다. 가장 흔히 사용된 것은 항상 옆에서 빠른 선택 가능 상태를 유지하고 아이콘만 남기기 위함입니다. 이 변형은 단순히 지시문으로igxDrawerMini 장식된 대체 미니 템플릿의 존재로 가능해집니다.

    미니 변형은 보편적인 환경에서 흔히 사용되므로, 반응 임계값을 설정pin 하고 비활성화했습니다:

    <igx-nav-drawer id="navigation" [pin]="true" [pinThreshold]="0">
      <ng-template igxDrawer>
        <span *ngFor="let item of navItems" igxDrawerItem [active]="item.text === selected" igxRipple (click)="navigate(item)">
          <igx-icon fontSet="material">{{ item.name }}</igx-icon>
          <span>{{ item.text }}</span>
        </span>
      </ng-template>
      <ng-template igxDrawerMini>
        <span *ngFor="let item of navItems" igxDrawerItem [active]="item.text === selected" igxRipple (click)="navigate(item)">
          <igx-icon fontSet="material">{{ item.name }}</igx-icon>
        </span>
      </ng-template>
    </igx-nav-drawer>
    

    Angular 라우터 사용

    Angular 라우터를 사용하려면 먼저 git을@angular/router 가져오고 라우터 인스턴스를 생성자로 만들어야 합니다. 그 다음 라우터를 이용해 링크 값을 내비게이션 항목을 정의해야 합니다.

    /* app.component.ts */
     ...
    
    export class AppComponent {
        public componentLinks = [
            {
                link: 'avatar',
                name: 'Avatar'
            },
            {
                link: 'badge',
                name: 'Badge'
            },
            {
                link: 'button-group',
                name: 'Button Group'
            }
        ];
    }
    

    템플릿 변수에 할당된 곳을 사용할routerLinkActive 수 있고, 그isActive 속성은 입력에 바인딩activeigxDrawerItem 하는 데 사용할 수 있습니다. 템플릿은<igx-nav-drawer> 다음과 같습니다:

    /* app.component.html */
    
    <!-- ... -->
    <ng-template igxDrawer>
      <nav>
        <span igxDrawerItem [isHeader]="true">Components</span>
    
        <span
          *ngFor="let item of componentLinks"
          routerLink="{{item.link}}"
          routerLinkActive
          #rla="routerLinkActive"
          igxDrawerItem
          igxRipple
          [active]="rla.isActive">
           {{item.name}}
        </span>
      </nav>
    </ng-template>
    <!-- ... -->
    

    마지막으로, RouterModule과 아이템 경로app.module.ts 파일을 불러와요:

    /*app.module.ts*/
    import { RouterModule } from '@angular/router';
    
    @NgModule([
        imports: [
            RouterModule,
      RouterModule.forRoot([
                {path: 'avatar', component: NavDrawerRoutingComponent},
                {path: 'badge', component: NavDrawerRoutingComponent},
                {path: 'button-group', component: NavDrawerRoutingComponent}
            ])
        ]
    ])
    

    위의 모든 단계가 완료되면 앱은 다음과 같이 표시됩니다.

    계층적 탐색

    템플릿 내에서IgxNavigationDrawerComponent​ ​IgxTreeComponentigxDrawer를 사용하여 다단계 계층 내비게이션을 만들 수 있습니다. 트리는 애플리케이션Routes 객체에서 직접 구성할 수 있습니다. 이를 달성하는 방법은 다음과 같습니다:

    <igx-nav-drawer [isOpen]="true" [enableGestures]="true" width="280px">
      <ng-template igxDrawer>
        <igx-tree>
          <igx-tree-node *ngFor="let route of routes">
            <a igxTreeNodeLink [routerLink]="route.path" routerLinkActive="route-selected-class">{{ route.data?.displayName }}</a>
            <igx-tree-node *ngFor="let child of route.children">
              <a igxTreeNodeLink [routerLink]="[route.path, child.path]" routerLinkActive="route-selected-class">{{ child.data?.displayName }}</a>
            </igx-tree-node>
          </igx-tree-node>
        </igx-tree>
      </ng-template>
    </igx-nav-drawer>
    
    메모

    이 예시에서는 를igxDrawerItem 사용하지 않고, 대신 직접 커스텀igxDrawer 콘텐츠를 채우고 있습니다. 이 경우에는 anigx-tree을 사용합니다.

    import { menusRoutes } from '../../menus-routing.module';
    
    @Component({
      selector: 'app-nav-drawer-hierarchical',
      templateUrl: './nav-drawer-hierarchical.component.html',
      styleUrls: ['./nav-drawer-hierarchical.component.scss'],
    })
    export class NavDrawerHierarchicalComponent {
      public routes = menusRoutes;
    }
    

    이 예시에서는 노드 내 링크 텍스트data를 시각화하는 데 사용되는 속성을 포함하는displayName 커스텀 라우팅igx-tree으로 경로를 채우고 있습니다. 예시Route는 다음과 같습니다:

    export const menusRoutes: Routes = [
      {
        component: NavDrawerHierarchicalComponent,
        path: 'navigation-drawer-hierarchical',
        data: { displayName: 'Hierarchical Drawer Menu' },
      },
    ];
    

    또한 경로의 속성에서children 추출한 자식 라우팅도 있습니다. 샘플은 두 가지 계층 구조를 보여주지만, 라우팅에 더 많은 계층이 있다면 트리 노드 템플릿에서 두 번째 계층 아래 계층을 정의하기만 하면 됩니다.

    메모

    빈 경로 리디렉션, 오류 경로, 페이지를 찾을 수 없음 등과 같은 일부 경로는 직접 시각화에 적합하지 않을 수 있습니다. 트리를 라우팅 개체에 바인딩하기 전에 구성 요소 논리의 개체에서 해당 경로를 제거할 수 있습니다.

    아래 예에서는 주제 이름 및 링크와 함께 사전 정의된 데이터를 사용하여 계층 구조의 기능을 보여줍니다. 이 구조를 통해 사용자는 기능적이고 자세한 탐색을 쉽게 생성할 수 있으며 각 요소를 링크로 표시할지 표시기로 표시할지 정의할 수 있습니다.

    스타일링

    내비게이션 드로어 스타일링을 시작하려면, 모든 테마 기능과 컴포넌트 믹싱이 있는 파일을 가져와index야 합니다:

    @use "igniteui-angular/theming" as *;
    
    // IMPORTANT: Prior to Ignite UI for Angular version 13 use:
    // @import '~igniteui-angular/lib/core/styles/themes/index';
    

    가장 간단한 방법을 따라, 내비게이션 드로워의 아이템을 스타일링하는 몇 가지 매개변수를 확장navdrawer-theme 하고 수용하는 새로운 테마를 만듭니다:

    $custom-theme: navdrawer-theme(
      $background: #2d313a,
      $item-active-background: #ecc256,
      $item-header-text-color: #ecc256,
    );
    

    보시다시피, 아이템navdrawer-theme의 기본 스타일링을 위한 유용한 파라미터들을 보여줍니다.

    마지막 단계는 애플리케이션에 구성 요소 테마를 포함하는 것입니다.

    @include css-vars($custom-theme);
    
    메모

    만약 컴포넌트가 ViewEncapsulation을 사용Emulated 한다면, 스타일을 적용하려면 이 캡슐화penetrate::ng-deep 필요합니다.

    :host {
      ::ng-deep { 
        @include css-vars($custom-theme);
      }
    }
    

    API 및 스타일 참조