본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

멀티셀렉트 컴포넌트

원문 보기 위키 갱신

멀티셀렉트 컴포넌트 (MultiSelect Component)

멀티셀렉트(MultiSelect)는 컬렉션에서 여러 항목을 동시에 선택할 수 있게 해주는 컴포넌트예요 ngModel과 options 배열을 이용한 기본 사용법부터 칩 표시, 필터, 그룹화, 가상 스크롤 같은 실무에서 자주 쓰는 기능까지 차근차근 다뤄요 접근성과 테마 설정 내용도 함께 담고 있으니 처음 배우는 분도 부담 없이 따라올 수 있어요

출처: 문서

본문

접근성

컴포넌트를 설명하는 값은 ariaLabelledBy 또는 ariaLabel 프롭으로 제공할 수 있어요. multiselect 컴포넌트는 combobox 역할을 가지고 있고, 여기에 aria-haspopup과 aria-expanded 속성도 함께 있어요. combobox와 팝업 사이의 관계는 팝업 listbox의 id를 참조하는 aria-controls 속성으로 만들어져요. 팝업 listbox는 listbox를 역할로 사용하며 aria-multiselectable이 활성화되어 있어요. 각 리스트 항목은 option 역할을 가지고 있고, aria-label, aria-selected, aria-disabled 속성도 함께 제공돼요. 헤더의 Checkbox 컴포넌트는 내부적으로 스크린 리더에만 보이는 숨겨진 네이티브 checkbox 엘리먼트를 사용해요. 읽어야 할 값은 locale API의 aria 프로퍼티에서 selectAll과 unselectAll 키로 정의돼요. 필터링이 활성화되어 있다면 filterInputProps를 정의해서 input 엘리먼트에 aria-* 프롭을 전달할 수 있어요. 닫기 버튼은 기본적으로 locale API의 aria 프로퍼티에서 close 키를 aria-label로 사용하는데, 이 값은 closeButtonProps로 재정의할 수 있어요.

기본

MultiSelect는 ngModel 프로퍼티와 options 컬렉션을 함께 사용하는 제어 컴포넌트로 동작해요. 옵션의 라벨과 값은 각각 optionLabel과 optionValue 프로퍼티로 정의돼요. optionLabel의 기본 프로퍼티 이름은 label이고, optionValue의 기본 프로퍼티 이름은 value예요. optionValue가 생략되고 객체에 value 프로퍼티가 없으면 객체 자체가 옵션의 값이 돼요. 옵션이 문자열 배열처럼 단순한 원시 값일 때는 optionLabel과 optionValue가 필요 없다는 점에 유의하세요.

import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MultiSelectModule } from 'primeng/multiselect';

interface City {
    name: string;
    code: string;
}

@Component({
    template: `
        <div class="card flex justify-center">
            <p-multiselect [options]="cities" [(ngModel)]="selectedCities" optionLabel="name" placeholder="Select Cities" [maxSelectedLabels]="3" class="w-full md:w-80" />
        </div>
    `,
    standalone: true,
    imports: [MultiSelectModule, FormsModule]
})
export class MultiselectBasicDemo implements OnInit {
    cities!: City[];
    selectedCities!: any[];

    ngOnInit() {
        this.cities = [
            { name: 'New York', code: 'NY' },
            { name: 'Rome', code: 'RM' },
            { name: 'London', code: 'LDN' },
            { name: 'Istanbul', code: 'IST' },
            { name: 'Paris', code: 'PRS' }
        ];
    }
}

칩

선택된 값은 기본적으로 쉼표로 구분된 목록으로 표시되는데, display를 chip으로 설정하면 칩 형태로 표시돼요.

import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MultiSelectModule } from 'primeng/multiselect';

interface City {
    name: string;
    code: string;
}

@Component({
    template: `
        <div class="card flex justify-center">
            <p-multiselect [options]="cities" [(ngModel)]="selectedCities" placeholder="Select Cities" optionLabel="name" display="chip" class="w-full md:w-80" />
        </div>
    `,
    standalone: true,
    imports: [MultiSelectModule, FormsModule]
})
export class MultiselectChipsDemo implements OnInit {
    cities!: City[];
    selectedCities!: City[];

    ngOnInit() {
        this.cities = [
            { name: 'New York', code: 'NY' },
            { name: 'Rome', code: 'RM' },
            { name: 'London', code: 'LDN' },
            { name: 'Istanbul', code: 'IST' },
            { name: 'Paris', code: 'PRS' }
        ];
    }
}

지우기 아이콘

showClear가 활성화되면 값을 지울 수 있는 지우기 아이콘이 표시돼요.

import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MultiSelectModule } from 'primeng/multiselect';

interface City {
    name: string;
    code: string;
}

@Component({
    template: `
        <div class="card flex justify-center">
            <p-multiselect [options]="cities" [(ngModel)]="selectedCities" optionLabel="name" placeholder="Select Cities" [maxSelectedLabels]="3" class="w-full md:w-80" [showClear]="true" />
        </div>
    `,
    standalone: true,
    imports: [MultiSelectModule, FormsModule]
})
export class MultiselectCleariconDemo implements OnInit {
    cities!: City[];
    selectedCities!: any[];

    ngOnInit() {
        this.cities = [
            { name: 'New York', code: 'NY' },
            { name: 'Rome', code: 'RM' },
            { name: 'London', code: 'LDN' },
            { name: 'Istanbul', code: 'IST' },
            { name: 'Paris', code: 'PRS' }
        ];
    }
}

비활성화

disabled가 있으면 엘리먼트를 편집하거나 포커스할 수 없어요.

import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MultiSelectModule } from 'primeng/multiselect';

interface City {
    name: string;
    code: string;
}

@Component({
    template: `
        <div class="card flex justify-center">
            <p-multiselect [options]="cities" [(ngModel)]="selectedCities" [disabled]="true" optionLabel="name" placeholder="Select Cities" class="w-full md:w-80" />
        </div>
    `,
    standalone: true,
    imports: [MultiSelectModule, FormsModule]
})
export class MultiselectDisabledDemo implements OnInit {
    cities!: City[];
    selectedCities!: City[];

    ngOnInit() {
        this.cities = [
            { name: 'New York', code: 'NY' },
            { name: 'Rome', code: 'RM' },
            { name: 'London', code: 'LDN' },
            { name: 'Istanbul', code: 'IST' },
            { name: 'Paris', code: 'PRS' }
        ];
    }
}

채움

variant 프로퍼티를 filled로 지정하면 기본 outlined 스타일보다 시각적으로 더 강조된 모습으로 컴포넌트가 표시돼요.

import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MultiSelectModule } from 'primeng/multiselect';

interface City {
    name: string;
    code: string;
}

@Component({
    template: `
        <div class="card flex justify-center">
            <p-multiselect [options]="cities" [(ngModel)]="selectedCities" variant="filled" optionLabel="name" placeholder="Select Cities" [maxSelectedLabels]="3" class="w-full md:w-80" />
        </div>
    `,
    standalone: true,
    imports: [MultiSelectModule, FormsModule]
})
export class MultiselectFilledDemo implements OnInit {
    cities!: City[];
    selectedCities!: any[];

    ngOnInit() {
        this.cities = [
            { name: 'New York', code: 'NY' },
            { name: 'Rome', code: 'RM' },
            { name: 'London', code: 'LDN' },
            { name: 'Istanbul', code: 'IST' },
            { name: 'Paris', code: 'PRS' }
        ];
    }
}

필터

MultiSelect는 filter 프로퍼티를 추가하면 활성화되는 내장 필터링을 제공해요.

import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MultiSelectModule } from 'primeng/multiselect';

interface City {
    name: string;
    code: string;
}

@Component({
    template: `
        <div class="card flex justify-center">
            <p-multiselect [options]="cities" [(ngModel)]="selectedCities" [filter]="true" optionLabel="name" placeholder="Select Cities" [maxSelectedLabels]="3" class="w-full md:w-80" />
        </div>
    `,
    standalone: true,
    imports: [MultiSelectModule, FormsModule]
})
export class MultiselectFilterDemo implements OnInit {
    cities!: City[];
    selectedCities!: City[];

    ngOnInit() {
        this.cities = [
            { name: 'New York', code: 'NY' },
            { name: 'Rome', code: 'RM' },
            { name: 'London', code: 'LDN' },
            { name: 'Istanbul', code: 'IST' },
            { name: 'Paris', code: 'PRS' }
        ];
    }
}

플로트 라벨

포커스를 받으면 입력 필드 위에 플로팅 라벨이 나타나요. 자세한 내용은 FloatLabel 문서를 참고하세요.

import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { FloatLabelModule } from 'primeng/floatlabel';
import { MultiSelectModule } from 'primeng/multiselect';

interface City {
    name: string;
    code: string;
}

@Component({
    template: `
        <div class="card flex flex-wrap justify-center items-end gap-4">
            <p-floatlabel class="w-full md:w-80">
                <p-multiselect id="over_label" [(ngModel)]="value1" [options]="cities" optionLabel="name" filter [maxSelectedLabels]="3" class="w-full" />
                <label for="over_label">Over Label</label>
            </p-floatlabel>
            <p-floatlabel class="w-full md:w-80" variant="in">
                <p-multiselect id="in_label" [(ngModel)]="value2" [options]="cities" optionLabel="name" filter [maxSelectedLabels]="3" class="w-full" />
                <label for="in_label">In Label</label>
            </p-floatlabel>
            <p-floatlabel class="w-full md:w-80" variant="on">
                <p-multiselect id="on_label" [(ngModel)]="value3" [options]="cities" optionLabel="name" filter [maxSelectedLabels]="3" class="w-full" />
                <label for="on_label">On Label</label>
            </p-floatlabel>
        </div>
    `,
    standalone: true,
    imports: [FloatLabelModule, MultiSelectModule, FormsModule]
})
export class MultiselectFloatlabelDemo implements OnInit {
    cities!: City[];
    value1!: City[];
    value2!: City[];
    value3!: City[];

    ngOnInit() {
        this.cities = [
            { name: 'New York', code: 'NY' },
            { name: 'Rome', code: 'RM' },
            { name: 'London', code: 'LDN' },
            { name: 'Istanbul', code: 'IST' },
            { name: 'Paris', code: 'PRS' }
        ];
    }
}

플루이드

fluid 프롭을 true로 설정하면 컴포넌트가 컨테이너의 전체 너비를 차지하게 돼요.

import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MultiSelectModule } from 'primeng/multiselect';

interface City {
    name: string;
    code: string;
}

@Component({
    template: `
        <div class="card flex justify-center">
            <p-multiselect [options]="cities" [(ngModel)]="selectedCities" optionLabel="name" placeholder="Select Cities" [maxSelectedLabels]="3" fluid />
        </div>
    `,
    standalone: true,
    imports: [MultiSelectModule, FormsModule]
})
export class MultiselectFluidDemo implements OnInit {
    cities!: City[];
    selectedCities!: any[];

    ngOnInit() {
        this.cities = [
            { name: 'New York', code: 'NY' },
            { name: 'Rome', code: 'RM' },
            { name: 'London', code: 'LDN' },
            { name: 'Istanbul', code: 'IST' },
            { name: 'Paris', code: 'PRS' }
        ];
    }
}

Group

중첩된 데이터 구조를 제공하면 옵션들을 그룹으로 묶을 수 있어요.

import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MultiSelectModule } from 'primeng/multiselect';
import { SelectItemGroup } from 'primeng/api';

interface City {
    name: string;
    code: string;
}

@Component({
    template: `
        <div class="card flex justify-center">
            <p-multiselect [options]="groupedCities" [group]="true" [(ngModel)]="selectedCities" placeholder="Select Cities" scrollHeight="250px" display="chip" class="w-full md:w-80">
                <ng-template let-group #group>
                    <div class="flex items-center">
                        <img src="https://primefaces.org/cdn/primeng/images/demo/flag/flag_placeholder.png" [class]="'mr-2 flag flag-' + group.value" style="width: 20px" />
                        <span>{{ group.label }}</span>
                    </div>
                </ng-template>
            </p-multiselect>
        </div>
    `,
    standalone: true,
    imports: [MultiSelectModule, FormsModule]
})
export class MultiselectGroupDemo {
    groupedCities!: SelectItemGroup[];
    selectedCities!: City[];

    constructor() {
        this.groupedCities = [
                    {
                        label: 'Germany',
                        value: 'de',
                        items: [
                            { label: 'Berlin', value: 'Berlin' },
                            { label: 'Frankfurt', value: 'Frankfurt' },
                            { label: 'Hamburg', value: 'Hamburg' },
                            { label: 'Munich', value: 'Munich' }
                        ]
                    },
                    {
                        label: 'USA',
                        value: 'us',
                        items: [
                            { label: 'Chicago', value: 'Chicago' },
                            { label: 'Los Angeles', value: 'Los Angeles' },
                            { label: 'New York', value: 'New York' },
                            { label: 'San Francisco', value: 'San Francisco' }
                        ]
                    },
                    {
                        label: 'Japan',
                        value: 'jp',
                        items: [
                            { label: 'Kyoto', value: 'Kyoto' },
                            { label: 'Osaka', value: 'Osaka' },
                            { label: 'Tokyo', value: 'Tokyo' },
                            { label: 'Yokohama', value: 'Yokohama' }
                        ]
                    }
                ];
    }
}

Ifta Label

IftaLabel은 필드 안에서 위쪽으로 정렬된 라벨을 만들 때 사용해요. 자세한 내용은 IftaLabel 문서를 참고하세요.

import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { IftaLabelModule } from 'primeng/iftalabel';
import { MultiSelectModule } from 'primeng/multiselect';

interface City {
    name: string;
    code: string;
}

@Component({
    template: `
        <div class="card flex justify-center">
            <p-iftalabel class="w-full md:w-80">
                <p-multiselect [(ngModel)]="selectedCities" inputId="ms_cities" [options]="cities" optionLabel="name" [filter]="true" [maxSelectedLabels]="3" class="w-full" />
                <label for="ms_cities">Cities</label>
            </p-iftalabel>
        </div>
    `,
    standalone: true,
    imports: [IftaLabelModule, MultiSelectModule, FormsModule]
})
export class MultiselectIftalabelDemo implements OnInit {
    cities!: City[];
    selectedCities!: City[];

    ngOnInit() {
        this.cities = [
            { name: 'New York', code: 'NY' },
            { name: 'Rome', code: 'RM' },
            { name: 'London', code: 'LDN' },
            { name: 'Istanbul', code: 'IST' },
            { name: 'Paris', code: 'PRS' }
        ];
    }
}

Invalid

invalid 상태는 ⁠invalid 속성을 사용해서 적용하며, 유효성 검사에 실패했음을 나타내고 Angular Forms와도 통합할 수 있어요.

import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MultiSelectModule } from 'primeng/multiselect';

interface City {
    name: string;
    code: string;
}

@Component({
    template: `
        <div class="card flex justify-center gap-4">
            <p-multiselect [options]="cities" [(ngModel)]="selectedCities1" [invalid]="value1" optionLabel="name" placeholder="Select Cities" [maxSelectedLabels]="3" class="w-full md:w-80" />
            <p-multiselect [options]="cities" [(ngModel)]="selectedCities2" [invalid]="value2" optionLabel="name" placeholder="Select Cities" [maxSelectedLabels]="3" class="w-full md:w-80" variant="filled" />
        </div>
    `,
    standalone: true,
    imports: [MultiSelectModule, FormsModule]
})
export class MultiselectInvalidDemo {
    value1: boolean = true;
    value2: boolean = true;
    cities: City[];
    selectedCities1!: City[];
    selectedCities2!: City[];
}

Loading State

로딩 상태는 loading 속성으로 사용할 수 있어요.

import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MultiSelectModule } from 'primeng/multiselect';

interface City {
    name: string;
    code: string;
}

@Component({
    template: `
        <div class="card flex justify-center">
            <p-multiselect [options]="cities" [(ngModel)]="selectedCities" [loading]="true" optionLabel="name" placeholder="Loading..." class="w-full md:w-80" />
        </div>
    `,
    standalone: true,
    imports: [MultiSelectModule, FormsModule]
})
export class MultiselectLoadingstateDemo implements OnInit {
    cities!: City[];
    selectedCities!: any[];

    ngOnInit() {
        this.cities = [
            { name: 'New York', code: 'NY' },
            { name: 'Rome', code: 'RM' },
            { name: 'London', code: 'LDN' },
            { name: 'Istanbul', code: 'IST' },
            { name: 'Paris', code: 'PRS' }
        ];
    }
}

reactiveforms-doc

MultiSelect는 리액티브 폼과도 함께 사용할 수 있어요. 이 경우 formControlName 속성을 사용해서 컴포넌트를 폼 컨트롤에 바인딩해요.

import { Component, inject } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { MessageModule } from 'primeng/message';
import { MultiSelectModule } from 'primeng/multiselect';
import { ToastModule } from 'primeng/toast';
import { ButtonModule } from 'primeng/button';
import { MessageService } from 'primeng/api';

interface City {
    name: string;
    code: string;
}

@Component({
    template: `
        <p-toast />
        <div class="card flex justify-center">
            <form [formGroup]="exampleForm" (ngSubmit)="onSubmit()" class="flex justify-center flex-col gap-4 w-full md:w-80">
                <div class="flex flex-col gap-1">
                    <p-multiselect [options]="cities" formControlName="city" optionLabel="name" placeholder="Select Cities" [maxSelectedLabels]="3" [fluid]="true" [invalid]="isInvalid('city')" />
                    @if (isInvalid('city')) {
                        <p-message severity="error" size="small" variant="simple">City is required.</p-message>
                    }
                </div>
                <button pButton severity="secondary" type="submit"><span pButtonLabel>Submit</span></button>
            </form>
        </div>
    `,
    standalone: true,
    imports: [MessageModule, MultiSelectModule, ToastModule, ButtonModule, ReactiveFormsModule],
    providers: [MessageService]
})
export class MultiselectReactiveformsDemo {
    private messageService = inject(MessageService);
    messageService = inject(MessageService);
    cities: City[];
    exampleForm: FormGroup | undefined;
    formSubmitted: boolean = false;

    constructor() {
        this.exampleForm = this.fb.group({
                    city: ['', Validators.required]
                });
    }

    onSubmit() {
        this.formSubmitted = true;
        if (this.exampleForm.valid) {
            this.messageService.add({ severity: 'success', summary: 'Success', detail: 'Form Submitted', life: 3000 });
            this.exampleForm.reset();
            this.formSubmitted = false;
        }
    }

    isInvalid(controlName: string) {
        const control = this.exampleForm.get(controlName);
        return control?.invalid && (control.touched || this.formSubmitted);
    }
}

Sizes

MultiSelect는 기본 크기 외에 small과 large 크기를 대안으로 제공해요.

import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MultiSelectModule } from 'primeng/multiselect';

interface City {
    name: string;
    code: string;
}

@Component({
    template: `
        <div class="card flex flex-col items-center gap-4">
            <p-multiselect [(ngModel)]="value1" [options]="cities" optionLabel="name" [maxSelectedLabels]="3" class="w-full md:w-80" size="small" placeholder="Small" />
            <p-multiselect [(ngModel)]="value2" [options]="cities" optionLabel="name" [maxSelectedLabels]="3" class="w-full md:w-80" placeholder="Normal" />
            <p-multiselect [(ngModel)]="value3" [options]="cities" optionLabel="name" [maxSelectedLabels]="3" class="w-full md:w-80" size="large" placeholder="Large" />
        </div>
    `,
    standalone: true,
    imports: [MultiSelectModule, FormsModule]
})
export class MultiselectSizesDemo implements OnInit {
    cities!: City[];
    value1: any[];
    value2: any[];
    value3: any[];

    ngOnInit() {
        this.cities = [
            { name: 'New York', code: 'NY' },
            { name: 'Rome', code: 'RM' },
            { name: 'London', code: 'LDN' },
            { name: 'Istanbul', code: 'IST' },
            { name: 'Paris', code: 'PRS' }
        ];
    }
}

Template

사용 가능한 옵션과 선택된 옵션은 각각 item과 selecteditems 템플릿으로 커스터마이징할 수 있어요. 또한 header, footer, filter 섹션도 템플릿으로 구성할 수 있어요.

import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ButtonModule } from 'primeng/button';
import { MultiSelectModule } from 'primeng/multiselect';
import { Country } from '@/domain/customer';

interface Country {
    name: string;
    code: string;
}

@Component({
    template: `
        <div class="card flex justify-center">
            <p-multiselect [options]="countries" [(ngModel)]="selectedCountries" placeholder="Select Countries" optionLabel="name" class="w-full md:w-80" display="chip">
                <ng-template let-country #item>
                    <div class="flex items-center gap-2">
                        <img src="https://primefaces.org/cdn/primeng/images/demo/flag/flag_placeholder.png" [class]="'flag flag-' + country.code.toLowerCase()" style="width: 18px" />
                        <div>{{ country.name }}</div>
                    </div>
                </ng-template>
                <ng-template #dropdownicon>
                    <i class="pi pi-map"></i>
                </ng-template>
                <ng-template #filtericon>
                    <i class="pi pi-map-marker"></i>
                </ng-template>
                <ng-template #header>
                    <div class="font-medium px-3 py-2">Available Countries</div>
                </ng-template>
                <ng-template #footer>
                    <div class="p-3 flex justify-between">
                        <p-button label="Add New" severity="secondary" text size="small" icon="pi pi-plus" />
                        <p-button label="Remove All" severity="danger" text size="small" icon="pi pi-times" />
                    </div>
                </ng-template>
            </p-multiselect>
        </div>
    `,
    standalone: true,
    imports: [ButtonModule, MultiSelectModule, FormsModule]
})
export class MultiselectTemplateDemo implements OnInit {
    countries!: Country[];
    selectedCountries!: Country[];

    ngOnInit() {
        this.countries = [
            { name: 'Australia', code: 'AU' },
            { name: 'Brazil', code: 'BR' },
            { name: 'China', code: 'CN' },
            { name: 'Egypt', code: 'EG' },
            { name: 'France', code: 'FR' },
            { name: 'Germany', code: 'DE' },
            { name: 'India', code: 'IN' },
            { name: 'Japan', code: 'JP' },
            { name: 'Spain', code: 'ES' },
            { name: 'United States', code: 'US' }
        ];
    }
}

templatedrivenforms-doc

import { Component, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MessageModule } from 'primeng/message';
import { MultiSelectModule } from 'primeng/multiselect';
import { ToastModule } from 'primeng/toast';
import { ButtonModule } from 'primeng/button';
import { MessageService } from 'primeng/api';

interface City {
    name: string;
    code: string;
}

@Component({
    template: `
        <p-toast />
        <div class="card flex justify-center">
            <form #exampleForm="ngForm" (ngSubmit)="onSubmit(exampleForm)" class="flex justify-center flex-col gap-4 w-full md:w-80">
                <div class="flex flex-col gap-1">
                    <p-multiselect
                        #city="ngModel"
                        [(ngModel)]="selectedCity"
                        [options]="cities"
                        optionLabel="name"
                        name="city"
                        placeholder="Select Cities"
                        [maxSelectedLabels]="3"
                        [invalid]="city.invalid && (city.touched || exampleForm.submitted)"
                        fluid
                        required
                    />
                    @if (city.invalid && (city.touched || exampleForm.submitted)) {
                        <p-message severity="error" size="small" variant="simple">City is required.</p-message>
                    }
                </div>
                <button pButton severity="secondary" type="submit"><span pButtonLabel>Submit</span></button>
            </form>
        </div>
    `,
    standalone: true,
    imports: [MessageModule, MultiSelectModule, ToastModule, ButtonModule, FormsModule],
    providers: [MessageService]
})
export class MultiselectTemplatedrivenformsDemo {
    private messageService = inject(MessageService);
    messageService = inject(MessageService);
    cities: City[];
    selectedCity: City | undefined;

    onSubmit(form: any) {
        if (form.valid) {
            this.messageService.add({ severity: 'success', summary: 'Success', detail: 'Form Submitted', life: 3000 });
            form.resetForm();
        }
    }
}

VirtualScroll

VirtualScrolling은 뷰포트에 한 번에 데이터의 일부만 보여줘서 옵션을 렌더링하는 효율적인 방법이에요. 엄청나게 많은 옵션을 다룰 때는 성능 문제를 피하려고 VirtualScrolling을 활성화하는 게 좋아요. 사용법도 간단해서 virtualScroll 속성을 true로 설정하고 virtualScrollItemSize로 항목의 높이를 지정하기만 하면 돼요.

import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MultiSelectModule } from 'primeng/multiselect';

@Component({
    template: `
        <div class="card flex justify-center">
            <p-multiselect
                [options]="items"
                [showToggleAll]="true"
                [selectAll]="selectAll"
                [(ngModel)]="selectedItems"
                optionLabel="label"
                [virtualScroll]="true"
                [virtualScrollItemSize]="43"
                placeholder="Select Cities"
                (onSelectAllChange)="onSelectAllChange($event)"
                [maxSelectedLabels]="3"
                class="w-full md:w-80"
                #ms
            >
                <ng-template #headercheckboxicon let-allSelected="checked" let-partialSelected="partialSelected">
                    <i class="pi pi-check" *ngIf="allSelected"></i>
                    <i class="pi pi-minus" *ngIf="partialSelected" [ngStyle]="{ color: 'var(--text-color)' }"></i>
                </ng-template>
            </p-multiselect>
        </div>
    `,
    standalone: true,
    imports: [MultiSelectModule, FormsModule]
})
export class MultiselectVirtualscrollDemo {
    items: any = Array.from({ length: 100000 }, (_, i) => ({ label: `Item #${i}`, value: i }));
    selectedItems!: any[];
    selectAll: boolean = false;

    onSelectAllChange(event) {
        this.selectedItems = event.checked ? [...this.ms.visibleOptions()] : [];
        this.selectAll = event.checked;
    }
}

Multi Select

MultiSelect는 컬렉션에서 여러 항목을 선택할 때 사용해요.

Props

Name Type Default Description
dt InputSignal undefined 컴포넌트의 스코프 디자인 토큰을 정의해요.
unstyled InputSignal undefined 컴포넌트를 스타일 없이 렌더링할지 여부를 나타내요.
pt InputSignal undefined 컴포넌트 내부의 DOM 요소에 속성을 전달할 때 사용해요.
ptOptions InputSignal undefined 컴포넌트의 passthrough(pt) 옵션을 설정할 때 사용해요.
required InputSignalWithTransform<boolean, unknown> false 값이 반드시 있어야 해요(설정된 경우).
invalid InputSignalWithTransform<boolean, unknown> false 설정하면 컴포넌트가 invalid 상태 스타일을 가져야 한다는 걸 지정해요.
disabled InputSignalWithTransform<boolean, unknown> false 설정하면 컴포넌트가 disabled 상태 스타일을 가져야 한다는 걸 지정해요.
name InputSignal undefined 설정하면 입력의 이름을 지정해요.
id string - 컴포넌트의 고유 식별자예요.
ariaLabel string - 접근성을 위해 입력에 라벨을 붙이는 문자열을 정의해요.
styleClass string - 요소의 스타일 클래스예요. (지원 중단됨)
panelStyle any - 오버레이 패널의 인라인 스타일이에요.
panelStyleClass string - 오버레이 패널 요소의 스타일 클래스예요.
inputId string - 컴포넌트에 정의된 라벨과 매칭할 포커스 입력의 식별자예요.
readonly boolean false 설정하면 컴포넌트를 편집할 수 없다는 걸 지정해요.
group boolean false 중첩된 옵션이 제공될 때 옵션을 그룹으로 표시할지 여부예요.
filter boolean true 지정하면 keyup 시 항목을 필터링하는 입력 필드를 표시해요.
filterPlaceHolder string - 필터 입력의 placeholder를 정의해요.
filterLocale string - 필터링에 사용할 로케일이에요. 기본 로케일은 호스트 환경의 현재 로케일이에요.
overlayVisible boolean false 옵션 패널의 표시 여부를 지정해요.
tabindex number 0 탭 순서에서 요소의 인덱스예요.
dataKey string - 옵션에서 값을 고유하게 식별하는 프로퍼티예요.
ariaLabelledBy string - 컴포넌트와 라벨(들) 사이의 관계를 설정해요. 값은 하나 이상의 요소 ID여야 해요.
displaySelectedLabel boolean - 선택된 항목의 라벨을 보여줄지, 아니면 기본 라벨을 사용할지 여부예요.
maxSelectedLabels number - 선택된 항목 라벨을 최대 몇 개까지 보여줄지 결정해요.
selectionLimit number - 선택할 수 있는 항목의 최대 개수예요.
selectedItemsLabel string - 최대 선택 라벨 수를 초과했을 때 표시할 라벨이에요. 예: ({0} items selected), text-overflow를 나타내는 "ellipsis" 키워드가 기본값이에요.
showToggleAll boolean true 헤더에 모든 항목을 한 번에 토글하는 체크박스를 표시할지 여부예요.
emptyFilterMessage string - 필터링 결과가 없을 때 표시할 텍스트예요.
emptyMessage string - 데이터가 없을 때 표시할 텍스트예요. i18n 번역 설정의 전역 값이 기본값이에요.
resetFilterOnHide boolean false 드롭다운을 숨길 때 필터 값을 지워요.
dropdownIcon string - 드롭다운 아이콘의 아이콘 클래스예요.
chipIcon string - 칩 아이콘의 아이콘 클래스예요.
optionLabel string - 옵션의 라벨 필드 이름이에요.
optionValue string - 옵션의 값 필드 이름이에요.
optionDisabled string - 옵션의 disabled 필드 이름이에요.
optionGroupLabel string label 옵션 그룹의 라벨 필드 이름이에요.
optionGroupChildren string items 옵션 그룹의 옵션 필드 이름이에요.
showHeader boolean true 헤더를 표시할지 여부예요.
filterBy string - 필터링이 활성화되면 filterBy가 검색 대상 필드(쉼표로 구분)를 결정해요.
scrollHeight string 200px 뷰포트의 높이(픽셀)예요. 목록의 높이가 이 값을 초과하면 스크롤바가 생겨요.
lazy boolean false 데이터를 lazy 방식으로 로드하고 상호작용할지 정의해요.
virtualScroll boolean false 스크롤 중에 데이터를 필요할 때 로드할지 여부예요.
loading boolean false multiselect가 로딩 상태인지 여부예요.
virtualScrollItemSize number - VirtualScrolling에서 목록 항목의 높이예요.
loadingIcon string - 로딩 상태에서 표시할 아이콘이에요.
virtualScrollOptions ScrollerOptions - scroller 기능을 사용할지 여부예요. scroller 컴포넌트의 프로퍼티들을 객체처럼 넣어서 사용할 수 있어요.
overlayOptions OverlayOptions - overlay API 기능을 사용할지 여부예요. overlay API의 프로퍼티들을 객체처럼 넣어서 사용할 수 있어요.
ariaFilterLabel string - 필터 입력에 라벨을 붙이는 문자열을 정의해요.
filterMatchMode "startsWith" | "contains" | "endsWith" | "equals" | "notEquals" | "in" | "lt" | "lte" | "gt" | "gte" contains 항목을 어떻게 필터링할지 정의해요.
tooltip string - 호버 시 툴팁에 표시할 안내 정보예요.
tooltipPosition "right" | "left" | "top" | "bottom" right 툴팁의 위치예요.
tooltipPositionStyle string absolute CSS position 타입이에요.
tooltipStyleClass string - 툴팁의 스타일 클래스예요.
autofocusFilter boolean false 오버레이가 표시될 때 필터 요소에 포커스를 적용해요.
display string comma 선택된 항목을 어떻게 표시할지 정의해요.
autocomplete string off autocomplete 활성화 여부를 정의해요.
showClear boolean false 활성화하면 값을 지울 수 있는 clear 아이콘이 표시돼요.
autofocus boolean false 설정하면 로드 시 컴포넌트가 자동으로 포커스를 받아야 한다는 걸 지정해요.
placeholder Signal - 선택된 항목이 없을 때 표시할 라벨이에요.
options any[] - 사용 가능한 옵션으로 표시할 객체 배열이에요.
filterValue string - 지정하면 필터가 이 값으로 표시돼요.
selectAll boolean - 모든 데이터가 선택되었는지 여부예요.
focusOnHover boolean true 옵션 위에 호버할 때 옵션에 포커스를 줄지 여부를 나타내요. 기본값은 optionLabel이에요.
filterFields any[] - 옵션을 필터링할 때 사용되는 필드예요. 기본값은 optionLabel이에요.
selectOnFocus boolean false 포커스 시 옵션을 선택할지 결정해요.
autoOptionFocus boolean false 오버레이 패널이 표시될 때 첫 번째 보이는 요소나 선택된 요소에 포커스를 줄지 여부예요.
highlightOnSelect boolean true 선택된 옵션에 highlight 클래스를 추가할지 여부예요.
size InputSignal<"small" | "large"> undefined 컴포넌트의 크기를 지정해요.
variant InputSignal<"outlined" | "filled"> undefined 컴포넌트의 입력 variant를 지정해요.
fluid InputSignalWithTransform<boolean, unknown> undefined 활성화하면 컨테이너의 100% 너비를 차지해요.
appendTo InputSignal 'self' 오버레이를 붙일 대상 요소예요. 유효한 값은 "body" 또는 다른 요소의 로컬 ng-template 변수예요(참고: 템플릿 변수에는 대괄호 바인딩을 사용하세요. 예를 들어 #mydiv를 변수 이름으로 가진 div 요소라면 [appendTo]="mydiv"처럼 사용해요).
motionOptions InputSignal ... 모션 옵션이에요.

Emits

Name Parameters Description
onChange event: MultiSelectChangeEvent 값이 변경될 때 호출되는 콜백이에요.
onFilter event: MultiSelectFilterEvent 데이터가 필터링될 때 호출되는 콜백이에요.
onFocus event: MultiSelectFocusEvent multiselect가 포커스를 받을 때 호출되는 콜백이에요.
onBlur event: MultiSelectBlurEvent multiselect가 포커스를 잃을 때 호출되는 콜백이에요.
onClick event: Event 컴포넌트가 클릭될 때 호출되는 콜백이에요.
onClear value: void 입력 필드가 지워질 때 호출되는 콜백이에요.
onPanelShow event: AnimationEvent 오버레이 패널이 보이게 될 때 호출되는 콜백이에요.
onPanelHide event: AnimationEvent 오버레이 패널이 숨겨질 때 호출되는 콜백이에요.
onLazyLoad event: MultiSelectLazyLoadEvent lazy 모드에서 새 데이터를 로드할 때 호출되는 콜백이에요.
onRemove event: MultiSelectRemoveEvent lazy 모드에서 새 데이터를 로드할 때 호출되는 콜백이에요.
onSelectAllChange event: MultiSelectSelectAllChangeEvent 모든 데이터가 선택될 때 호출되는 콜백이에요.

템플릿

이름 타입 설명
item TemplateRef<MultiSelectItemTemplateContext> 커스텀 아이템 템플릿이에요.
group TemplateRef<MultiSelectGroupTemplateContext> 커스텀 그룹 템플릿이에요.
loader TemplateRef 커스텀 로더 템플릿이에요.
header TemplateRef 커스텀 헤더 템플릿이에요.
filter TemplateRef 커스텀 필터 템플릿이에요.
footer TemplateRef 커스텀 푸터 템플릿이에요.
emptyfilter TemplateRef 커스텀 빈 필터 템플릿이에요.
empty TemplateRef 커스텀 빈 템플릿이에요.
selecteditems TemplateRef<MultiSelectSelectedItemsTemplateContext> 커스텀 선택 아이템 템플릿이에요.
loadingicon TemplateRef 커스텀 로딩 아이콘 템플릿이에요.
filtericon TemplateRef 커스텀 필터 아이콘 템플릿이에요.
removetokenicon TemplateRef 커스텀 토큰 제거 아이콘 템플릿이에요.
chipicon TemplateRef 커스텀 칩 아이콘 템플릿이에요.
clearicon TemplateRef 커스텀 클리어 아이콘 템플릿이에요.
dropdownicon TemplateRef 커스텀 드롭다운 아이콘 템플릿이에요.
itemcheckboxicon TemplateRef 커스텀 아이템 체크박스 아이콘 템플릿이에요.
headercheckboxicon TemplateRef 커스텀 헤더 체크박스 아이콘 템플릿이에요.

메서드

이름 파라미터 반환 타입 설명
updateModel value: any, event: any void 모델 값을 업데이트해요.
show isFocus: any void 패널을 표시해요.
hide isFocus: any void 패널을 숨겨요.

Pass Through 옵션

이름 타입 설명
root PassThroughOption<HTMLDivElement, I> 루트의 DOM 엘리먼트에 속성을 전달할 때 사용해요.
labelContainer PassThroughOption<HTMLDivElement, I> 라벨 컨테이너의 DOM 엘리먼트에 속성을 전달할 때 사용해요.
label PassThroughOption<HTMLDivElement, I> 라벨의 DOM 엘리먼트에 속성을 전달할 때 사용해요.
clearIcon PassThroughOption<SVGElement, I> 클리어 아이콘의 DOM 엘리먼트에 속성을 전달할 때 사용해요.
chipItem PassThroughOption<HTMLDivElement, I> 칩 아이템의 DOM 엘리먼트에 속성을 전달할 때 사용해요.
pcChip ChipPassThrough Chip 컴포넌트에 속성을 전달할 때 사용해요.
dropdown PassThroughOption<HTMLDivElement, I> 드롭다운의 DOM 엘리먼트에 속성을 전달할 때 사용해요.
loadingIcon PassThroughOption<HTMLSpanElement, I> 로딩 아이콘의 DOM 엘리먼트에 속성을 전달할 때 사용해요.
dropdownIcon PassThroughOption<SVGElement, I> 드롭다운 아이콘의 DOM 엘리먼트에 속성을 전달할 때 사용해요.
overlay PassThroughOption<HTMLDivElement, I> 오버레이의 DOM 엘리먼트에 속성을 전달할 때 사용해요.
header PassThroughOption<HTMLDivElement, I> 헤더의 DOM 엘리먼트에 속성을 전달할 때 사용해요.
pcHeaderCheckbox CheckboxPassThrough 헤더 체크박스 컴포넌트에 속성을 전달할 때 사용해요.
pcFilterContainer IconFieldPassThrough IconField 컴포넌트에 속성을 전달할 때 사용해요.
pcFilter InputTextPassThrough InputText 컴포넌트에 속성을 전달할 때 사용해요.
pcFilterIconContainer InputIconPassThrough InputIcon 컴포넌트에 속성을 전달할 때 사용해요.
filterIcon PassThroughOption<SVGElement, I> 필터 아이콘의 DOM 엘리먼트에 속성을 전달할 때 사용해요.
listContainer PassThroughOption<HTMLDivElement, I> 리스트 컨테이너의 DOM 엘리먼트에 속성을 전달할 때 사용해요.
list PassThroughOption<HTMLUListElement, I> 리스트의 DOM 엘리먼트에 속성을 전달할 때 사용해요.
optionGroup PassThroughOption<HTMLLIElement, I> 옵션 그룹의 DOM 엘리먼트에 속성을 전달할 때 사용해요.
option PassThroughOption<HTMLLIElement, I> 옵션의 DOM 엘리먼트에 속성을 전달할 때 사용해요.
pcOptionCheckbox CheckboxPassThrough 옵션 체크박스 컴포넌트에 속성을 전달할 때 사용해요.
emptyMessage PassThroughOption<HTMLLIElement, I> 빈 메시지의 DOM 엘리먼트에 속성을 전달할 때 사용해요.

테마

CSS 클래스

클래스 설명
p-multiselect 루트 엘리먼트의 클래스 이름이에요.
p-multiselect-label-container 라벨 컨테이너 엘리먼트의 클래스 이름이에요.
p-multiselect-label 라벨 엘리먼트의 클래스 이름이에요.
p-multiselect-chip-item 칩 아이템 엘리먼트의 클래스 이름이에요.
p-multiselect-chip 칩 엘리먼트의 클래스 이름이에요.
p-multiselect-chip-icon 칩 아이콘 엘리먼트의 클래스 이름이에요.
p-multiselect-dropdown 드롭다운 엘리먼트의 클래스 이름이에요.
p-multiselect-loading-icon 로딩 아이콘 엘리먼트의 클래스 이름이에요.
p-multiselect-dropdown-icon 드롭다운 아이콘 엘리먼트의 클래스 이름이에요.
p-multiselect-overlay 오버레이 엘리먼트의 클래스 이름이에요.
p-multiselect-header 헤더 엘리먼트의 클래스 이름이에요.
p-multiselect-filter-container 필터 컨테이너 엘리먼트의 클래스 이름이에요.
p-multiselect-filter 필터 엘리먼트의 클래스 이름이에요.
p-multiselect-list-container 리스트 컨테이너 엘리먼트의 클래스 이름이에요.
p-multiselect-list 리스트 엘리먼트의 클래스 이름이에요.
p-multiselect-option-group 옵션 그룹 엘리먼트의 클래스 이름이에요.
p-multiselect-option 옵션 엘리먼트의 클래스 이름이에요.
p-multiselect-empty-message 빈 메시지 엘리먼트의 클래스 이름이에요.
p-autocomplete-clear-icon 클리어 아이콘의 클래스 이름이에요.

디자인 토큰

토큰 CSS 변수 설명
multiselect.background --p-multiselect-background 루트의 배경이에요.
multiselect.disabled.background --p-multiselect-disabled-background 루트의 비활성 상태 배경이에요.
multiselect.filled.background --p-multiselect-filled-background 루트의 채움 상태 배경이에요.
multiselect.filled.hover.background --p-multiselect-filled-hover-background 루트의 채움 상태 호버 배경이에요.
multiselect.filled.focus.background --p-multiselect-filled-focus-background 루트의 채움 상태 포커스 배경이에요.
multiselect.border.color --p-multiselect-border-color 루트의 테두리 색상이에요.
multiselect.hover.border.color --p-multiselect-hover-border-color 루트의 호버 테두리 색상이에요.
multiselect.focus.border.color --p-multiselect-focus-border-color 루트의 포커스 테두리 색상이에요.
multiselect.invalid.border.color --p-multiselect-invalid-border-color 루트의 유효하지 않은 상태 테두리 색상이에요.
multiselect.color --p-multiselect-color 루트의 색상이에요.
multiselect.disabled.color --p-multiselect-disabled-color 루트의 비활성 상태 색상이에요.
multiselect.placeholder.color --p-multiselect-placeholder-color 루트의 플레이스홀더 색상이에요.
multiselect.invalid.placeholder.color --p-multiselect-invalid-placeholder-color 루트의 유효하지 않은 상태 플레이스홀더 색상이에요.
multiselect.shadow --p-multiselect-shadow 루트의 그림자예요.
multiselect.padding.x --p-multiselect-padding-x 루트의 가로 패딩이에요.
multiselect.padding.y --p-multiselect-padding-y 루트의 세로 패딩이에요.
multiselect.border.radius --p-multiselect-border-radius 루트의 테두리 반경이에요.
multiselect.focus.ring.width --p-multiselect-focus-ring-width 루트의 포커스 링 너비예요.
multiselect.focus.ring.style --p-multiselect-focus-ring-style 루트의 포커스 링 스타일이에요.
multiselect.focus.ring.color --p-multiselect-focus-ring-color 루트의 포커스 링 색상이에요.
multiselect.focus.ring.offset --p-multiselect-focus-ring-offset 루트의 포커스 링 오프셋이에요.
multiselect.focus.ring.shadow --p-multiselect-focus-ring-shadow 루트의 포커스 링 그림자예요.
multiselect.transition.duration --p-multiselect-transition-duration 루트의 전환 지속 시간이에요.
multiselect.sm.font.size --p-multiselect-sm-font-size 루트의 sm 폰트 크기예요.
multiselect.sm.padding.x --p-multiselect-sm-padding-x 루트의 sm 가로 패딩이에요.
multiselect.sm.padding.y --p-multiselect-sm-padding-y 루트의 sm 세로 패딩이에요.
multiselect.lg.font.size --p-multiselect-lg-font-size 루트의 lg 폰트 크기예요.
multiselect.lg.padding.x --p-multiselect-lg-padding-x 루트의 lg 가로 패딩이에요.
multiselect.lg.padding.y --p-multiselect-lg-padding-y 루트의 lg 세로 패딩이에요.
multiselect.dropdown.width --p-multiselect-dropdown-width 드롭다운의 너비예요.
multiselect.dropdown.color --p-multiselect-dropdown-color 드롭다운의 색상이에요.
multiselect.overlay.background --p-multiselect-overlay-background 오버레이의 배경이에요.
multiselect.overlay.border.color --p-multiselect-overlay-border-color 오버레이의 테두리 색상이에요.
multiselect.overlay.border.radius --p-multiselect-overlay-border-radius 오버레이의 테두리 반경이에요.
multiselect.overlay.color --p-multiselect-overlay-color 오버레이의 색상이에요.
multiselect.overlay.shadow --p-multiselect-overlay-shadow 오버레이의 그림자예요.
multiselect.list.padding --p-multiselect-list-padding 리스트의 패딩이에요.
multiselect.list.gap --p-multiselect-list-gap 리스트의 간격이에요.
multiselect.list.header.padding --p-multiselect-list-header-padding 리스트의 헤더 패딩이에요.
multiselect.option.focus.background --p-multiselect-option-focus-background 옵션의 포커스 배경이에요.
multiselect.option.selected.background --p-multiselect-option-selected-background 옵션의 선택 상태 배경이에요.
multiselect.option.selected.focus.background --p-multiselect-option-selected-focus-background 옵션의 선택 상태 포커스 배경이에요.
multiselect.option.color --p-multiselect-option-color 옵션의 색상이에요.
multiselect.option.focus.color --p-multiselect-option-focus-color 옵션의 포커스 색상이에요.
multiselect.option.selected.color --p-multiselect-option-selected-color 옵션의 선택 상태 색상이에요.
multiselect.option.selected.focus.color --p-multiselect-option-selected-focus-color 옵션의 선택 상태 포커스 색상이에요.
multiselect.option.padding --p-multiselect-option-padding 옵션의 패딩이에요.
multiselect.option.border.radius --p-multiselect-option-border-radius 옵션의 테두리 반경이에요.
multiselect.option.gap --p-multiselect-option-gap 옵션의 간격이에요.
multiselect.option.group.background --p-multiselect-option-group-background 옵션 그룹의 배경이에요.
multiselect.option.group.color --p-multiselect-option-group-color 옵션 그룹의 색상이에요.
multiselect.option.group.font.weight --p-multiselect-option-group-font-weight 옵션 그룹의 폰트 두께예요.
multiselect.option.group.padding --p-multiselect-option-group-padding 옵션 그룹의 패딩이에요.
multiselect.clear.icon.color --p-multiselect-clear-icon-color 클리어 아이콘의 색상이에요.
multiselect.chip.border.radius --p-multiselect-chip-border-radius 칩의 테두리 반경이에요.
multiselect.empty.message.padding --p-multiselect-empty-message-padding 빈 메시지의 패딩이에요.

더 알아보기 (Learn more)

이 문서에는 원문에서 추출한 별도의 관련 문서 링크가 없어요.