Angular 목록 보기 구성 요소 개요

    Ignite UI for Angular 항목 행을 표시하고 하나 이상의 헤더 항목과 목록 항목 검색 및 필터링을 지원합니다. 각 목록 항목은 완전히 템플릿화 가능하며 유효한 HTML 또는 Angular 구성 요소를 지원합니다. 또한 목록 구성 요소는 내장된 패닝 기능, 빈 상태 및 로드 상태에 대한 템플릿을 제공하고 IgxForOf 지시문을 사용하여 대규모 목록에 대한 가상화를 지원합니다.

    Angular List Example

    다음 예는 이름전화번호 속성이 있는 연락처로 채워진 목록을 나타냅니다. IgxList 구성 요소는 igx-avatarigx-icon 사용하여 사용자 경험을 풍부하게 하고 연락처 즐겨찾기에 대한 아바타 사진 및 다양한 아이콘 설정 기능을 제공합니다. 또한 목록 보기에는 필터링 파이프를 사용하여 달성된 정렬 기능이 표시됩니다.

    Getting Started with Ignite UI for Angular List

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

    ng add igniteui-angular
    

    Ignite UI for Angular에 대한 전체 소개를 보려면 시작하기 항목을 읽어보세요.

    다음 단계는 IgxListModule에서 app.module.ts 파일.

    Note

    이 구성 요소를 사용하려면 터치 상호 작용이 예상대로 작동하려면 응용 프로그램의 루트 모듈에서 HammerModule 가져와야 합니다..

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

    또는 16.0.0부터 IgxListComponent 독립 실행형 종속성으로 가져오거나 IGX_LIST_DIRECTIVES 토큰을 사용하여 구성 요소와 모든 지원 구성 요소 및 지시어를 가져올 수 있습니다.

    // home.component.ts
    
    import { HammerModule } from '@angular/platform-browser';
    import { IGX_LIST_DIRECTIVES } from 'igniteui-angular';
    // import { IGX_LIST_DIRECTIVES } from '@infragistics/igniteui-angular'; for licensed package
    
    @Component({
        selector: 'app-home',
        template: `
        <igx-list>
            <igx-list-item isHeader="true">Header</igx-list-item>
            <igx-list-item>Item 1</igx-list-item>
            <igx-list-item>Item 2</igx-list-item>
            <igx-list-item>Item 3</igx-list-item>
        </igx-list>
        `,
        styleUrls: ['home.component.scss'],
        standalone: true,
        imports: [IGX_LIST_DIRECTIVES, HammerModule]
        /* or imports: [IgxListComponent, IgxListItemComponent, HammerModule] */
    })
    export class HomeComponent {}
    

    이제 Ignite UI for Angular 모듈 또는 지시문을 가져왔으므로 igx-list 구성 요소 사용을 시작할 수 있습니다.

    Using the Angular List

    그런 다음 연락처 구성 요소의 템플릿에서 목록을 만들 수 있습니다. 하지만 현재(또는 미래의 특정 시점) 목록에 항목이 없으면 어떻게 될까요? 이 경우 Angular 목록은 목록이 비어 있을 때 사용되는 기본 템플릿을 제공합니다. igxEmptyList 지시문을 사용하면 언제든지 빈 목록 모양에 대한 자체 템플릿을 제공할 수 있습니다. 이 경우 기본 템플릿은 사용되지 않습니다.

    <!--contacts.component.html-->
    
    <igx-list>
        <ng-template igxEmptyList>
            <p class="empty">No contacts! :(</p>
        </ng-template>
    </igx-list>
    

    빈 템플릿에 대한 스타일은 다음과 같습니다.

    /* contacts.component.css */
    
    .empty {
        color: rgba(0, 153, 255, 1);
        font-size: 25px;
        font-weight: 600;
        text-shadow: 2px 1px 2px rgba(150, 150, 150, 1);
    }
    

    모든 것이 잘 되었다면 빈 목록은 다음과 같습니다.

    때로는 데이터 로딩이 지연될 수 있습니다. 이 경우 목록의 isLoading 속성을 true로 설정할 수 있으며 기본 템플릿은 진행 중인 데이터 로드 프로세스에 대해 사용자에게 알립니다. igxDataLoading 지시문을 사용하여 자체 로딩 템플릿을 제공할 수도 있습니다.

    <!--contacts.component.html-->
    
    <igx-list>
        <ng-template igxDataLoading>
            <p class="loading">Patience, we are currently loading your data...</p>
        </ng-template>
    </igx-list>
    
    /* contacts.component.css */
    
    .loading {
        color: rgba(255, 153, 0, 1);
        font-size: 25px;
        font-weight: 600;
        text-shadow: 2px 1px 2px rgba(150, 150, 150, 1);
    }
    

    Add List Items

    목록이 비어 있을 때를 위한 템플릿이 있으면 좋지만 이제 몇 가지 항목을 추가해 보겠습니다. 다음 코드를 추가하여 간단한 항목 목록을 얻을 수 있습니다.

    <!--contacts.component.html-->
    
    <igx-list>
        <igx-list-item isHeader="true">Header</igx-list-item>
        <igx-list-item>Item 1</igx-list-item>
        <igx-list-item>Item 2</igx-list-item>
        <igx-list-item>Item 3</igx-list-item>
    </igx-list>
    

    모든 것이 순조롭게 진행되면 브라우저에 다음이 표시됩니다.

    게임을 좀 더 강화하고 목록 항목을 강화해 보겠습니다. 이름 아래에 이름과 전화번호가 표시되는 Angular 연락처 목록을 만들고 싶다고 가정해 보겠습니다. 구성 요소 TypeScript 파일에서 연락처 목록을 정의할 수 있습니다.

    // contacts.component.ts
    ...
    public contacts = [{
        name: "Terrance Orta",
        phone: "770-504-2217"
    }, {
        name: "Richard Mahoney",
        phone: "423-676-2869"
    }, {
        name: "Donna Price",
        phone: "859-496-2817"
    }, {
        name: "Lisa Landers",
        phone: "901-747-3428"
    }, {
        name: "Dorothy H. Spencer",
        phone: "573-394-9254"
    }];
    

    이제 렌더링할 데이터가 있으므로 일부 마크업을 설정해 보겠습니다. 기본적으로 스타일을 지정하려면 목록 항목과 함께 제공되는 일부 지시문을 사용할 수 있습니다.

    다음 예제에서 그 중 일부를 어떻게 사용할 수 있는지 살펴보겠습니다.

    <!--contacts.component.html-->
    
    <igx-list>
      <igx-list-item isHeader="true">
        Contacts
      </igx-list-item>
      <igx-list-item *ngFor="let contact of contacts">
        <h4 igxListLineTitle>{{ contact.name }}</h4>
        <p igxListLineSubTitle>{{ contact.phone }}</p>
      </igx-list-item>
    </igx-list>
    

    igxListLineTitleigxListLineSubTitle 지시어 모두 목록 항목에 기본 모양을 제공합니다.

    결국 우리의 Angular 목록은 다음과 같아야 합니다.

    Adding Avatar and Icons

    IgxList 구성 요소와 함께 다른 구성 요소 중 일부를 사용하여 경험을 풍부하게 하고 일부 기능을 추가할 수 있습니다. 이름과 전화번호 왼쪽에 멋진 사진 아바타가 있을 수 있습니다. 또한 사용자가 연락처를 즐겨찾기에 추가할 수 있도록 오른쪽에 별표 아이콘을 추가할 수 있습니다. 이를 위해 IgxAvatarIgxIcon 모듈을 가져와 app.module.ts 파일로 가져옵니다.

    // app.module.ts
    
    ...
    import {
        IgxListModule,
        IgxAvatarModule,
        IgxIconModule
    } from 'igniteui-angular';
    // import { IgxListModule, IgxAvatarModule, IgxIconModule } from '@infragistics/igniteui-angular'; for licensed package
    
    @NgModule({
        ...
        imports: [..., IgxAvatarModule, IgxIconModule],
    })
    export class AppModule {}
    

    다음으로 아바타의 photo 소스와 연락처의 즐겨찾기 상태를 나타내는 isFavorite 속성과 같은 추가 정보를 연락처 개체에 추가해야 합니다.

    // contacts.component.ts
    
    public contacts = [{
        name: 'Terrance Orta',
        phone: '770-504-2217',
        photo: 'https://randomuser.me/api/portraits/men/27.jpg',
        isFavorite: false
    }, {
        name: 'Richard Mahoney',
        phone: '423-676-2869',
        photo: 'https://randomuser.me/api/portraits/men/1.jpg',
        isFavorite: true
    }, {
        name: 'Donna Price',
        phone: '859-496-2817',
        photo: 'https://randomuser.me/api/portraits/women/50.jpg',
        isFavorite: false
    }, {
        name: 'Lisa Landers',
        phone: '901-747-3428',
        photo: 'https://randomuser.me/api/portraits/women/3.jpg',
        isFavorite: false
    }, {
        name: 'Dorothy H. Spencer',
        phone: '573-394-9254',
        photo: 'https://randomuser.me/api/portraits/women/67.jpg',
        isFavorite: true
    }];
    

    좋습니다. 이제 연락처 목록의 템플릿을 업데이트하여 아바타와 아이콘을 표시해 보겠습니다. 이번에도 목록 지시문 중 일부를 사용하여 이를 수행할 수 있습니다.

    <!--contacts.component.html-->
    
    <igx-list>
      <igx-list-item isHeader="true">
        Contacts
      </igx-list-item>
      <igx-list-item #item *ngFor="let contact of contacts;">
          <igx-avatar igxListThumbnail [src]="contact.photo" shape="circle"></igx-avatar>
          <h4 igxListLineTitle>{{ contact.name }}</h4>
          <p igxListLineSubTitle class="phone">{{ contact.phone }}</p>
          <span igxListLine>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dicta, laborum.</span>
          <igx-icon igxListAction [color]="contact.isFavorite ? 'orange' : 'lightgray'" (click)="toggleFavorite(item)">star</igx-icon>
      </igx-list-item>
    </igx-list>
    
    • igxListThumbnail 목록 항목 시작 부분에 일종의 미디어를 추가해야 하는 경우에 사용됩니다. 지시문은 기본 위치와 간격을 제공하는 컨테이너의 igx-avatar 사례에서 대상 요소를 래핑합니다.
    • igxListAction 일종의 작업이나 메타데이터(예: 스위치, 라디오 버튼, 확인란 등)가 있는 목록 항목에 사용됩니다. 이 경우 작업은 igx-icon으로 표시됩니다. 이번에도 지시문은 올바른 위치와 간격을 갖는 컨테이너에 대상 요소를 래핑합니다.
    • igxListLine​ ​igxListThumbnailigxListAction 사이에 일부 텍스트가 필요한 경우 사용하기 위한 것입니다. 이 지시문은 텍스트 위치, 간격 및 정렬이 다른 두 지시문과 잘 어울리는지 확인합니다.

    다음으로 우리는 Igx아이콘 토글하는 구성 요소 즐겨찾기 연락처 개체의 속성입니다.

    // contacts.component.ts
    
    ...
    toggleFavorite(item: IgxListItem) {
        const contact = this.contacts[item.index - 1];
        contact.isFavorite = !contact.isFavorite;
    }
    

    또한--ig-size CSS 사용자 정의 속성을 사용하여 사용자가 목록의 크기를 선택할 수 있도록 허용하겠습니다. IgxButtonGroupModule을 가져오고 IgxButtonGroup을 사용하여 모든 크기 값을 표시하면 됩니다. 이렇게 하면 하나가 선택될 때마다 목록의 크기가 업데이트됩니다.

    // app.module.ts
    ...
    import { IgxButtonGroupModule } from 'igniteui-angular';
    // import { IgxButtonGroupModule } from '@infragistics/igniteui-angular'; for licensed package
    
    @NgModule({
        imports: [..., IgxButtonGroupModule]
    })
    
    <!--contacts.component.html-->
    
    <igx-buttongroup [values]="sizes" (selected)="selectSize($event)"></igx-buttongroup>
    ...
    <igx-list>
        ...
    </igx-list>
    
    // contacts.component.ts
    
    public size = 'large';
    public sizes;
    
    public ngOnInit() {
        this.sizes = [
            { label: 'large', selected: this.size === 'large', togglable: true },
            { label: 'medium', selected: this.size === 'medium', togglable: true },
            { label: 'small', selected: this.size === 'small', togglable: true }
        ];
    }
    
    public selectSize(event: any) {
        this.size = this.sizes[event.index].label;
    }
    
    
    @HostBinding('style.--ig-size')
    protected get sizeStyle() {
        return `var(--ig-size-${this.size})`;
    }
    

    그리고 모든 작업의 결과는 다음과 같습니다.

    List Items Panning

    이제 연락처와 전화번호가 포함된 아름다운 Angular 목록이 있으므로 연락처에 전화하는 기능을 구현해 보는 것은 어떨까요? IgxList 목록 항목 패닝에 대한 완벽한 솔루션이 있습니다. 이렇게 하려면 다음 단계를 구현해야 합니다.

    • allowLeftPanning 및/또는 allowRightPanning 속성을 사용하여 패닝을 활성화합니다.
    • 왼쪽 및/또는 오른쪽 패닝을 위한 템플릿 정의
    • 목록 항목의 패닝 이벤트를 처리하고 원하는 작업을 수행합니다.

    다음 예에서는 왼쪽 및 오른쪽 패닝을 모두 처리하는 방법을 보여줍니다. 오른쪽 패닝에 대한 이벤트 핸들러는 토스트 메시지를 표시합니다. 왼쪽 패닝에 대한 이벤트 핸들러는 IgxList에서 항목을 삭제합니다.

    Note

    목록 항목 제거는 애플리케이션 작업이라는 점에 유의하세요. IgxList 에는 데이터 소스에 대한 참조가 없기 때문에 IgxList 자체는 데이터 소스에서 항목을 제거할 수 없습니다.

    예제의 HTML 코드는 다음과 같습니다.

    <!-- contacts.component.html -->
    
    <igx-list [allowLeftPanning]="true" [allowRightPanning]="true"
      (leftPan)="leftPanPerformed($event)" (rightPan)="rightPanPerformed($event)">
      <ng-template igxListItemLeftPanning>
        <div class="listItemLeftPanningStyle">
          <igx-icon [color]="white" style="margin-left:10px">delete</igx-icon>Delete
        </div>
      </ng-template>
      <ng-template igxListItemRightPanning>
        <div class="listItemRightPanningStyle">
          <igx-icon [color]="white" style="margin-right:10px">call</igx-icon>Dial
        </div>
      </ng-template>
      <igx-list-item isHeader="true">Contacts</igx-list-item>
      <igx-list-item #item *ngFor="let contact of contacts">
        <igx-avatar igxListThumbnail [src]="contact.photo" shape="circle"></igx-avatar>
        <h4 igxListLineTitle>{{ contact.name }}</h4>
        <p igxListLineSubTitle class="phone">{{ contact.phone }}</p>
        <igx-icon igxListAction [color]="contact.isFavorite ? 'orange' : 'lightgray'" (click)="toggleFavorite(item)">star</igx-icon>
      </igx-list-item>
    </igx-list>
    
    <igx-toast #toast></igx-toast>
    

    위의 예는 여기에서 찾을 수 있는 일부 CSS 스타일을 사용하고 있습니다.

    /* contacts.component.css */
    
    igx-icon {
        cursor: pointer;
        user-select: none;
    }
    
    .listItemLeftPanningStyle {
        display: flex;
        flex-direction: row-reverse;
        background-color:orange;
        color: white;
        width: 100%;
        padding-right: 10px;
        align-items: center;
    }
    
    .listItemRightPanningStyle {
        display: flex;
        flex-direction: row;
        background-color:limegreen;
        color: white;
        width: 100%;
        padding-left: 10px;
        align-items: center;
    }
    

    마지막으로 패닝 이벤트를 처리하는 TypeScript 코드는 다음과 같습니다.

    // contacts.component.ts
    
    ...
    @ViewChild('toast')
    public toast: IgxToastComponent;
    
    public rightPanPerformed(args) {
      args.keepItem = true;
      this.toast.message = 'Dialing ' + this.contacts[args.item.index - 1].name;
      this.toast.open();
    }
    
    public leftPanPerformed(args) {
      args.keepItem = false;
      setTimeout((idx = args.item.index - 1) => {
        this.toast.message = 'Contact ' + this.contacts[idx].name + ' removed.';
        this.toast.open();
        this.contacts.splice(idx, 1);
      }, 500);
    }
    
    ...
    
    Note

    목록 항목을 패닝할 때 패닝 이벤트를 내보내려면 도달해야 하는 임계값이 있습니다. IgxListpanEndTriggeringThreshold 속성을 사용하여 임계값을 변경할 수 있습니다. 기본적으로 이 속성의 값은 0.5입니다. 이는 목록 항목 너비의 50%를 의미합니다.

    이제 목록 항목을 직접 이동해 보세요.

    Angular filter list

    목록이 좋아 보이지만 이름으로 연락처를 검색할 수 있다면 더 좋지 않을까요? 필터링 파이프를 사용하면 쉽게 이를 달성할 수 있습니다. 이렇게 해보자.

    먼저 Angular 구성 요소 템플릿의 맨 위에 입력 필드를 추가하고 이를 searchContact 라는 구성 요소의 속성에 바인딩해 보겠습니다.

    <!--contacts.component.html-->
    
    <igx-input-group type="search" class="search">
        <igx-prefix>
            <igx-icon>search</igx-icon>
        </igx-prefix>
        <input #search igxInput placeholder="Search Contacts" [(ngModel)]="searchContact">
        <igx-suffix *ngIf="search.value.length > 0" (click)="searchContact = null">
            <igx-icon>clear</igx-icon>
        </igx-suffix>
    </igx-input-group>
    

    이제 app.module.ts 파일에서 IgxFilterModuleIgxInputGroupModule 가져오고 연락처 구성 요소에서 IgxFilterOptions 가져올 차례입니다.

    // app.module.ts
    ...
    import { IgxFilterModule, IgxInputGroupModule } from 'igniteui-angular';
    // import { IgxFilterModule, IgxInputGroupModule } from '@infragistics/igniteui-angular'; for licensed package
    
    @NgModule({
        imports: [..., IgxFilterModule, IgxInputGroupModule]
    })
    
    // contacts.component.ts
    ...
    import { IgxFilterOptions } from 'igniteui-angular';
    // import { IgxFilterOptions } from '@infragistics/igniteui-angular'; for licensed package
    
    @Component({...})
    export class ContactListComponent {
        public searchContact: string;
        ...
        get filterContacts(): IgxFilterOptions {
            const fo = new IgxFilterOptions();
            fo.key = 'name';
            fo.inputValue = this.searchContact;
            return fo;
        }
    }
    

    IgxFilterOptions를 가져온 후에는 searchContact 속성이 업데이트될 때마다 파이프에서 사용할 필터링 옵션을 반환하는 새로운 getter 메서드를 등록해야 합니다. 필터가 작동하려면 연락처 개체를 필터링할 key 등록해야 합니다. 우리의 경우에는 각 연락처의 name 됩니다. IgxFilterOptions 개체에 등록해야 하는 두 번째 속성은 연락처 이름을 비교할 때 확인해야 하는 값입니다. 이는 연락처 목록 위의 입력 필드에 바인딩된 searchContact 속성입니다.

    마지막으로 필터링 파이프를 사용하기 전에 연락처 데이터에 필터링 파이프를 적용해야 합니다. 따라서 템플릿에 다음을 추가하기만 하면 됩니다.

    <!--contacts.component.html-->
    
    <igx-list-item *ngFor="let contact of contacts | igxFilter: filterContacts; let i = index">
        ...
    </igx-list-item>
    

    List Item Selection

    이미 알고 계시겠지만 목록 항목은 선택 상태를 제공하지 않습니다. 그러나 응용 프로그램에서 어떤 항목이 선택되었는지 추적하기 위해 목록이 필요한 경우 이를 달성할 수 있는 방법에 대한 예를 제공합니다. 당신이 해야 할 일은 구성 요소나 목록이 바인딩된 데이터의 상태를 추적하는 것뿐입니다.

    다음은 목록이 바인딩된 데이터에서 나오는 상태 추적을 기반으로 테마의 보조 500 색상에 따라 목록에 배경색을 적용하는 예입니다.

    우리가 하고 있는 일은 각 데이터 멤버에 추가로 selected 속성을 추가하는 것입니다. 기본값은 false 입니다. 목록 항목을 클릭하면 데이터 컬렉션에서 selected 모든 속성을 재설정하고 클릭한 항목에 해당하는 속성을 true로 설정합니다. 선택한 속성을 기반으로 목록 항목에 선택한 배경을 제공하는 CSS 클래스를 적용합니다.

    <igx-list>
        <igx-list-item isHeader="true">Contacts</igx-list-item>
        <igx-list-item [ngClass]="contact.selected ? 'selected' : ''"
                        (click)="selectItem(contact)"
                        *ngFor="let contact of contacts | igxFilter: filterContacts;">
            <igx-avatar igxListThumbnail [src]="contact.photo" shape="circle"></igx-avatar>
            <span igxListLineTitle>{{ contact.name }}</span>
            <span igxListLineSubTitle>{{ contact.phone }}</span>
            <igx-icon igxListAction [style.color]="contact.isFavorite ? 'orange' : 'lightgray'" (click)="toggleFavorite(contact, $event)">star</igx-icon>
        </igx-list-item>
    </igx-list>
    
    public selectItem(item) {
        if (!item.selected) {
            this.contacts.forEach(c => c.selected = false);
            item.selected = true;
        }
    }
    
    .selected {
        background-color: hsla(var(--igx-secondary-500))
    }
    

    Applying theme to the list component

    목록의 배경을 어떻게 변경할 수 있는지 살펴보겠습니다. 먼저 index.scss를 구성 요소 .scss 파일로 가져와야 합니다.

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

    그런 다음 구성 요소에 대한 테마를 만들어야 합니다.

    :host ::ng-deep {
        $my-list-theme: list-theme(
            $background: #0568ab
        );
    
        @include list($my-list-theme);
    }
    

    위 코드의 결과는

    Note

    컴포넌트 .scss 파일에 컴포넌트 테마를 생성하는 경우 뷰 캡슐화를 전달하기 위해::ng-deep 사용해야 합니다. 그렇지 않으면 새 테마가 작동하지 않습니다! 자세한 내용은 구성요소 테마를 참조하세요.

    목록 구성요소에 대해 변경할 수 있는 매개변수의 전체 목록은 IgxListComponent 스타일을 참조하세요.

    API References

    이 기사에서는 Angular 목록 구성 요소에 대해 많은 내용을 다루었습니다. 연락처 항목 목록을 만들었습니다. 아바타 및 아이콘과 같은 목록 항목 내의 Ignite UI for Angular 사용했습니다. 일부 사용자 정의 항목 레이아웃을 만들고 스타일을 지정했습니다. 마지막으로 목록 필터링을 추가했습니다. 목록 구성 요소에는 아래에 나열된 몇 가지 API가 더 있습니다.

    사용된 추가 Angular 구성요소:

    Theming Dependencies

    Additional Resources

    우리 커뮤니티는 활동적이며 항상 새로운 아이디어를 환영합니다.