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

ion-select

원문 보기 위키 갱신

옵션(또는 여러 옵션)을 고를 때 쓰는 폼 컨트롤 컴포넌트예요. 사용자가 select를 누르면 모든 옵션이 크고 고르기 쉬운 목록으로 표시되는 다이얼로그가 나타나요.

출처: 문서

본문

Encapsulation: shadow

Select는 옵션 집합에서 하나 또는 여러 개의 옵션을 선택하는 폼 컨트롤이에요. 사용자가 select를 탭하면 모든 옵션이 크고 선택하기 쉬운 목록으로 표시되는 다이얼로그가 나타나요.

Select는 자식으로 <ion-select-option> 요소를 함께 써야 해요. 자식 옵션에 value 속성이 없으면 해당 옵션의 텍스트가 값으로 사용돼요.

<ion-select>에 value를 설정하면 그 값에 해당하는 옵션이 선택돼요.

Labels

라벨은 select를 설명하기 위해 사용해야 해요. 라벨은 시각적으로도 사용할 수 있고, 사용자가 select에 포커스했을 때 스크린 리더가 읽어 주기도 해요. 그래서 사용자가 select의 의도를 이해하기 쉬워져요. Select에는 라벨을 지정하는 여러 방법이 있어요:

  • label 속성: 평문 텍스트 라벨을 쓸 때 사용해요
  • label 슬롯: 커스텀 HTML 라벨을 쓸 때 사용해요
  • aria-label: 스크린 리더용 라벨을 제공하되 시각적인 라벨은 추가하지 않아요

Label Placement

라벨은 기본적으로 자기 콘텐츠의 너비만큼 차지해요. 개발자는 labelPlacement 속성을 이용해 라벨이 제어 요소 기준으로 어디에 배치될지 정할 수 있어요. 여기서는 label 속성을 사용했지만, labelPlacement는 label 슬롯과도 함께 쓸 수 있어요.

JavaScript

index.html

<ion-list>
  <ion-item>
    <ion-select label="Default label" placeholder="Favorite Fruit">
      <ion-select-option value="apple">Apple</ion-select-option>
      <ion-select-option value="banana">Banana</ion-select-option>
      <ion-select-option value="orange">Orange</ion-select-option>
    </ion-select>
  </ion-item>

  <ion-item>
    <ion-select label="Fixed label" label-placement="fixed" placeholder="Favorite fruit">
      <ion-select-option value="apple">Apple</ion-select-option>
      <ion-select-option value="banana">Banana</ion-select-option>
      <ion-select-option value="orange">Orange</ion-select-option>
    </ion-select>
  </ion-item>

  <ion-item>
    <ion-select label="Stacked label" label-placement="stacked">
      <ion-select-option value="apple">Apple</ion-select-option>
      <ion-select-option value="banana">Banana</ion-select-option>
      <ion-select-option value="orange">Orange</ion-select-option>
    </ion-select>
  </ion-item>

  <ion-item>
    <ion-select label="Floating label" label-placement="floating">
      <ion-select-option value="apple">Apple</ion-select-option>
      <ion-select-option value="banana">Banana</ion-select-option>
      <ion-select-option value="orange">Orange</ion-select-option>
    </ion-select>
  </ion-item>
</ion-list>

Angular

src/app/example.component.html

<ion-list>
  <ion-item>
    <ion-select label="Default label" placeholder="Favorite Fruit">
      <ion-select-option value="apple">Apple</ion-select-option>
      <ion-select-option value="banana">Banana</ion-select-option>
      <ion-select-option value="orange">Orange</ion-select-option>
    </ion-select>
  </ion-item>

  <ion-item>
    <ion-select label="Fixed label" label-placement="fixed" placeholder="Favorite fruit">
      <ion-select-option value="apple">Apple</ion-select-option>
      <ion-select-option value="banana">Banana</ion-select-option>
      <ion-select-option value="orange">Orange</ion-select-option>
    </ion-select>
  </ion-item>

  <ion-item>
    <ion-select label="Stacked label" label-placement="stacked">
      <ion-select-option value="apple">Apple</ion-select-option>
      <ion-select-option value="banana">Banana</ion-select-option>
      <ion-select-option value="orange">Orange</ion-select-option>
    </ion-select>
  </ion-item>

  <ion-item>
    <ion-select label="Floating label" label-placement="floating">
      <ion-select-option value="apple">Apple</ion-select-option>
      <ion-select-option value="banana">Banana</ion-select-option>
      <ion-select-option value="orange">Orange</ion-select-option>
    </ion-select>
  </ion-item>
</ion-list>

src/app/example.component.ts

import { Component } from '@angular/core';
import { IonItem, IonList, IonSelect, IonSelectOption } from '@ionic/angular';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonItem, IonList, IonSelect, IonSelectOption],
})
export class ExampleComponent {}

React

import React from 'react';
import { IonItem, IonList, IonSelect, IonSelectOption } from '@ionic/react';

function Example() {
  return (
    <IonList>
      <IonItem>
        <IonSelect label="Default label" placeholder="Favorite Fruit">
          <IonSelectOption value="apple">Apple</IonSelectOption>
          <IonSelectOption value="banana">Banana</IonSelectOption>
          <IonSelectOption value="orange">Orange</IonSelectOption>
        </IonSelect>
      </IonItem>

      <IonItem>
        <IonSelect label="Fixed label" labelPlacement="fixed" placeholder="Favorite fruit">
          <IonSelectOption value="apple">Apple</IonSelectOption>
          <IonSelectOption value="banana">Banana</IonSelectOption>
          <IonSelectOption value="orange">Orange</IonSelectOption>
        </IonSelect>
      </IonItem>

      <IonItem>
        <IonSelect label="Stacked label" labelPlacement="stacked">
          <IonSelectOption value="apple">Apple</IonSelectOption>
          <IonSelectOption value="banana">Banana</IonSelectOption>
          <IonSelectOption value="orange">Orange</IonSelectOption>
        </IonSelect>
      </IonItem>

      <IonItem>
        <IonSelect label="Floating label" labelPlacement="floating">
          <IonSelectOption value="apple">Apple</IonSelectOption>
          <IonSelectOption value="banana">Banana</IonSelectOption>
          <IonSelectOption value="orange">Orange</IonSelectOption>
        </IonSelect>
      </IonItem>
    </IonList>
  );
}
export default Example;

Vue

<template>
  <ion-list>
    <ion-item>
      <ion-select label="Default label" placeholder="Favorite Fruit">
        <ion-select-option value="apple">Apple</ion-select-option>
        <ion-select-option value="banana">Banana</ion-select-option>
        <ion-select-option value="orange">Orange</ion-select-option>
      </ion-select>
    </ion-item>

    <ion-item>
      <ion-select label="Fixed label" label-placement="fixed" placeholder="Favorite fruit">
        <ion-select-option value="apple">Apple</ion-select-option>
        <ion-select-option value="banana">Banana</ion-select-option>
        <ion-select-option value="orange">Orange</ion-select-option>
      </ion-select>
    </ion-item>

    <ion-item>
      <ion-select label="Stacked label" label-placement="stacked">
        <ion-select-option value="apple">Apple</ion-select-option>
        <ion-select-option value="banana">Banana</ion-select-option>
        <ion-select-option value="orange">Orange</ion-select-option>
      </ion-select>
    </ion-item>

    <ion-item>
      <ion-select label="Floating label" label-placement="floating">
        <ion-select-option value="apple">Apple</ion-select-option>
        <ion-select-option value="banana">Banana</ion-select-option>
        <ion-select-option value="orange">Orange</ion-select-option>
      </ion-select>
    </ion-item>
  </ion-list>
</template>

<script setup lang="ts">
  import { IonItem, IonList, IonSelect, IonSelectOption } from '@ionic/vue';
</script>

Label Slot

평문 텍스트 라벨은 label 속성으로 전달해야 하지만, 커스텀 HTML이 필요하다면 대신 label 슬롯으로 전달할 수 있어요.

JavaScript

index.html

<ion-select label-placement="stacked" aria-label="Favorite Fruit">
  <ion-icon slot="start" name="heart" aria-hidden="true"></ion-icon>
  <div slot="label">
    Favorite Fruit
    <ion-text color="medium">(optional)</ion-text>
  </div>
  <ion-select-option value="apple">Apple</ion-select-option>
  <ion-select-option value="banana">Banana</ion-select-option>
  <ion-select-option value="orange">Orange</ion-select-option>
</ion-select>

index.ts

import { defineCustomElements } from '@ionic/core/loader';

import { addIcons } from 'ionicons';
import { heart } from 'ionicons/icons';

/* Core CSS required for Ionic components to work properly */
import '@ionic/core/css/core.css';

/* Basic CSS for apps built with Ionic */
import '@ionic/core/css/normalize.css';
import '@ionic/core/css/structure.css';
import '@ionic/core/css/typography.css';

/* Optional CSS utils that can be commented out */
import '@ionic/core/css/padding.css';
import '@ionic/core/css/float-elements.css';
import '@ionic/core/css/text-alignment.css';
import '@ionic/core/css/text-transformation.css';
import '@ionic/core/css/flex-utils.css';
import '@ionic/core/css/display.css';

/**
 * Ionic Dark Palette
 * -----------------------------------------------------
 * For more information, please see:
 * https://ionicframework.com/docs/theming/dark-mode
 */

// import '@ionic/core/css/palettes/dark.always.css';
// import '@ionic/core/css/palettes/dark.class.css';
import '@ionic/core/css/palettes/dark.system.css';

/* Theme variables */
import './theme/variables.css';

/**
 * On Ionicons 7.2+ these icons
 * get mapped to a kebab-case key.
 * Alternatively, developers can do:
 * addIcons({ 'heart': heart });
 */
addIcons({ heart });

defineCustomElements();

Angular

src/app/example.component.html

<ion-select labelPlacement="stacked" aria-label="Favorite Fruit">
  <ion-icon slot="start" name="heart" aria-hidden="true"></ion-icon>
  <div slot="label">
    Favorite Fruit
    <ion-text color="medium">(optional)</ion-text>
  </div>
  <ion-select-option value="apple">Apple</ion-select-option>
  <ion-select-option value="banana">Banana</ion-select-option>
  <ion-select-option value="orange">Orange</ion-select-option>
</ion-select>

src/app/example.component.ts

import { Component } from '@angular/core';
import { IonIcon, IonSelect, IonSelectOption, IonText } from '@ionic/angular';

import { addIcons } from 'ionicons';
import { heart } from 'ionicons/icons';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonIcon, IonSelect, IonSelectOption, IonText],
})
export class ExampleComponent {
  constructor() {
    /**
     * Any icons you want to use in your application
     * can be registered in app.component.ts and then
     * referenced by name anywhere in your application.
     */
    addIcons({ heart });
  }
}

React

import React from 'react';
import { IonIcon, IonSelect, IonSelectOption, IonText } from '@ionic/react';
import { heart } from 'ionicons/icons';

function Example() {
  return (
    <IonSelect labelPlacement="stacked" aria-label="Favorite Fruit">
      <IonIcon slot="start" icon={heart} aria-hidden="true"></IonIcon>
      <div slot="label">
        Favorite Fruit
        <IonText color="medium">(optional)</IonText>
      </div>
      <IonSelectOption value="apple">Apple</IonSelectOption>
      <IonSelectOption value="banana">Banana</IonSelectOption>
      <IonSelectOption value="orange">Orange</IonSelectOption>
    </IonSelect>
  );
}
export default Example;

Vue

<template>
  <ion-select label-placement="stacked" aria-label="Favorite Fruit">
    <ion-icon slot="start" :icon="heart" aria-hidden="true"></ion-icon>
    <div slot="label">
      Favorite Fruit
      <ion-text color="medium">(optional)</ion-text>
    </div>
    <ion-select-option value="apple">Apple</ion-select-option>
    <ion-select-option value="banana">Banana</ion-select-option>
    <ion-select-option value="orange">Orange</ion-select-option>
  </ion-select>
</template>

<script setup lang="ts">
  import { IonIcon, IonSelect, IonSelectOption, IonText } from '@ionic/vue';
  import { heart } from 'ionicons/icons';
</script>

No Visible Label

보이는 라벨이 필요 없더라도, select가 스크린 리더에 접근 가능하도록 개발자는 여전히 aria-label을 제공해야 해요.

JavaScript

index.html

<ion-select aria-label="Favorite Fruit" placeholder="Select fruit">
  <ion-select-option value="apple">Apple</ion-select-option>
  <ion-select-option value="banana">Banana</ion-select-option>
  <ion-select-option value="orange">Orange</ion-select-option>
</ion-select>

Angular

src/app/example.component.html

<ion-select aria-label="Favorite Fruit" placeholder="Select fruit">
  <ion-select-option value="apple">Apple</ion-select-option>
  <ion-select-option value="banana">Banana</ion-select-option>
  <ion-select-option value="orange">Orange</ion-select-option>
</ion-select>

src/app/example.component.ts

import { Component } from '@angular/core';
import { IonSelect, IonSelectOption } from '@ionic/angular';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonSelect, IonSelectOption],
})
export class ExampleComponent {}

React

import React from 'react';
import { IonSelect, IonSelectOption } from '@ionic/react';

function Example() {
  return (
    <IonSelect aria-label="Favorite Fruit" placeholder="Select fruit">
      <IonSelectOption value="apple">Apple</IonSelectOption>
      <IonSelectOption value="banana">Banana</IonSelectOption>
      <IonSelectOption value="orange">Orange</IonSelectOption>
    </IonSelect>
  );
}
export default Example;

Vue

<template>
  <ion-select aria-label="Favorite Fruit" placeholder="Select fruit">
    <ion-select-option value="apple">Apple</ion-select-option>
    <ion-select-option value="banana">Banana</ion-select-option>
    <ion-select-option value="orange">Orange</ion-select-option>
  </ion-select>
</template>

<script setup lang="ts">
  import { IonSelect, IonSelectOption } from '@ionic/vue';
</script>

Single Selection

기본적으로 select는 사용자가 한 개의 옵션만 선택할 수 있게 해요. alert 인터페이스는 사용자에게 라디오 버튼 스타일의 옵션 목록을 보여줘요. select 컴포넌트의 value는 선택된 옵션의 value 값을 받아요.

단일 선택에 대한 키보드 상호작용은 아래 Keyboard Interactions 섹션에 설명되어 있어요.

JavaScript

index.html

<ion-list>
  <ion-item>
    <ion-select aria-label="Food" placeholder="Select food">
      <ion-select-option value="apples">Apples</ion-select-option>
      <ion-select-option value="oranges">Oranges</ion-select-option>
      <ion-select-option value="bananas">Bananas</ion-select-option>
    </ion-select>
  </ion-item>
</ion-list>

Angular

src/app/example.component.html

<ion-list>
  <ion-item>
    <ion-select aria-label="Food" placeholder="Select food">
      <ion-select-option value="apples">Apples</ion-select-option>
      <ion-select-option value="oranges">Oranges</ion-select-option>
      <ion-select-option value="bananas">Bananas</ion-select-option>
    </ion-select>
  </ion-item>
</ion-list>

src/app/example.component.ts

import { Component } from '@angular/core';
import { IonItem, IonList, IonSelect, IonSelectOption } from '@ionic/angular';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonItem, IonList, IonSelect, IonSelectOption],
})
export class ExampleComponent {}

React

import React from 'react';
import { IonItem, IonList, IonSelect, IonSelectOption } from '@ionic/react';

function Example() {
  return (
    <IonList>
      <IonItem>
        <IonSelect aria-label="Food" placeholder="Select food">
          <IonSelectOption value="apples">Apples</IonSelectOption>
          <IonSelectOption value="oranges">Oranges</IonSelectOption>
          <IonSelectOption value="bananas">Bananas</IonSelectOption>
        </IonSelect>
      </IonItem>
    </IonList>
  );
}
export default Example;

Vue

<template>
  <ion-list>
    <ion-item>
      <ion-select aria-label="Food" placeholder="Select food">
        <ion-select-option value="apples">Apples</ion-select-option>
        <ion-select-option value="oranges">Oranges</ion-select-option>
        <ion-select-option value="bananas">Bananas</ion-select-option>
      </ion-select>
    </ion-item>
  </ion-list>
</template>

<script setup lang="ts">
  import { IonItem, IonList, IonSelect, IonSelectOption } from '@ionic/vue';
</script>

Multiple Selection

select에 multiple 속성을 추가하면 사용자가 여러 옵션을 선택할 수 있어요. 여러 옵션을 선택할 수 있을 때는 alert, popover 또는 modal 오버레이가 사용자에게 체크박스 스타일의 옵션 목록을 보여줘요. select 컴포넌트의 value는 선택된 모든 옵션 값의 배열을 받아요.

Note

action-sheet 인터페이스는 다중 선택을 지원하지 않아요.

다중 선택에 대한 키보드 상호작용은 아래 Keyboard Interactions 섹션에 설명되어 있어요.

JavaScript

index.html

<ion-list>
  <ion-item>
    <ion-select multiple="true" aria-label="Fruits" placeholder="Select All That Apply">
      <ion-select-option value="apples">Apples</ion-select-option>
      <ion-select-option value="oranges">Oranges</ion-select-option>
      <ion-select-option value="bananas">Bananas</ion-select-option>
    </ion-select>
  </ion-item>
</ion-list>

Angular

src/app/example.component.html

<ion-list>
  <ion-item>
    <ion-select multiple="true" aria-label="Fruits" placeholder="Select All That Apply">
      <ion-select-option value="apples">Apples</ion-select-option>
      <ion-select-option value="oranges">Oranges</ion-select-option>
      <ion-select-option value="bananas">Bananas</ion-select-option>
    </ion-select>
  </ion-item>
</ion-list>

src/app/example.component.ts

import { Component } from '@angular/core';
import { IonItem, IonList, IonSelect, IonSelectOption } from '@ionic/angular';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonItem, IonList, IonSelect, IonSelectOption],
})
export class ExampleComponent {}

React

import React from 'react';
import { IonItem, IonList, IonSelect, IonSelectOption } from '@ionic/react';

function Example() {
  return (
    <IonList>
      <IonItem>
        <IonSelect multiple={true} aria-label="Fruits" placeholder="Select All That Apply">
          <IonSelectOption value="apples">Apples</IonSelectOption>
          <IonSelectOption value="oranges">Oranges</IonSelectOption>
          <IonSelectOption value="bananas">Bananas</IonSelectOption>
        </IonSelect>
      </IonItem>
    </IonList>
  );
}
export default Example;

Vue

<template>
  <ion-list>
    <ion-item>
      <ion-select multiple="true" aria-label="Fruits" placeholder="Select All That Apply">
        <ion-select-option value="apples">Apples</ion-select-option>
        <ion-select-option value="oranges">Oranges</ion-select-option>
        <ion-select-option value="bananas">Bananas</ion-select-option>
      </ion-select>
    </ion-item>
  </ion-list>
</template>

<script setup lang="ts">
  import { IonItem, IonList, IonSelect, IonSelectOption } from '@ionic/vue';
</script>

Interfaces

기본적으로 select는 ion-alert를 사용해 옵션 오버레이를 alert로 열어요. interface 속성에 각각 action-sheet, popover, modal을 전달하면 인터페이스를 ion-action-sheet, ion-popover, ion-modal로 바꿀 수 있어요. 각 인터페이스의 제한 사항에 대해서는 다른 섹션들을 계속 읽어 주세요.

Alert

JavaScript

index.html

<ion-select interface="alert" aria-label="Food" placeholder="Select food">
  <ion-select-option value="apples">Apples</ion-select-option>
  <ion-select-option value="oranges">Oranges</ion-select-option>
  <ion-select-option value="bananas">Bananas</ion-select-option>
</ion-select>

Angular

src/app/example.component.html

<ion-select interface="alert" aria-label="Food" placeholder="Select food">
  <ion-select-option value="apples">Apples</ion-select-option>
  <ion-select-option value="oranges">Oranges</ion-select-option>
  <ion-select-option value="bananas">Bananas</ion-select-option>
</ion-select>

src/app/example.component.ts

import { Component } from '@angular/core';
import { IonSelect, IonSelectOption } from '@ionic/angular';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonSelect, IonSelectOption],
})
export class ExampleComponent {}

React

import React from 'react';
import { IonSelect, IonSelectOption } from '@ionic/react';

function Example() {
  return (
    <IonSelect interface="alert" aria-label="Food" placeholder="Select food">
      <IonSelectOption value="apples">Apples</IonSelectOption>
      <IonSelectOption value="oranges">Oranges</IonSelectOption>
      <IonSelectOption value="bananas">Bananas</IonSelectOption>
    </IonSelect>
  );
}
export default Example;

Vue

<template>
  <ion-select interface="alert" aria-label="Food" placeholder="Select food">
    <ion-select-option value="apples">Apples</ion-select-option>
    <ion-select-option value="oranges">Oranges</ion-select-option>
    <ion-select-option value="bananas">Bananas</ion-select-option>
  </ion-select>
</template>

<script setup lang="ts">
  import { IonSelect, IonSelectOption } from '@ionic/vue';
</script>

Action Sheet

JavaScript

index.html

<ion-select interface="action-sheet" aria-label="Food" placeholder="Select food">
  <ion-select-option value="apples">Apples</ion-select-option>
  <ion-select-option value="oranges">Oranges</ion-select-option>
  <ion-select-option value="bananas">Bananas</ion-select-option>
</ion-select>

Angular

src/app/example.component.html

<ion-select interface="action-sheet" aria-label="Food" placeholder="Select food">
  <ion-select-option value="apples">Apples</ion-select-option>
  <ion-select-option value="oranges">Oranges</ion-select-option>
  <ion-select-option value="bananas">Bananas</ion-select-option>
</ion-select>

src/app/example.component.ts

import { Component } from '@angular/core';
import { IonSelect, IonSelectOption } from '@ionic/angular';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonSelect, IonSelectOption],
})
export class ExampleComponent {}

React

import React from 'react';
import { IonSelect, IonSelectOption } from '@ionic/react';

function Example() {
  return (
    <IonSelect interface="action-sheet" aria-label="Food" placeholder="Select food">
      <IonSelectOption value="apples">Apples</IonSelectOption>
      <IonSelectOption value="oranges">Oranges</IonSelectOption>
      <IonSelectOption value="bananas">Bananas</IonSelectOption>
    </IonSelect>
  );
}
export default Example;

Vue

<template>
  <ion-select interface="action-sheet" aria-label="Food" placeholder="Select food">
    <ion-select-option value="apples">Apples</ion-select-option>
    <ion-select-option value="oranges">Oranges</ion-select-option>
    <ion-select-option value="bananas">Bananas</ion-select-option>
  </ion-select>
</template>

<script setup lang="ts">
  import { IonSelect, IonSelectOption } from '@ionic/vue';
</script>

Popover

JavaScript

index.html

<ion-select interface="popover" aria-label="Food" placeholder="Select food">
  <ion-select-option value="apples">Apples</ion-select-option>
  <ion-select-option value="oranges">Oranges</ion-select-option>
  <ion-select-option value="bananas">Bananas</ion-select-option>
</ion-select>

Angular

src/app/example.component.html

<ion-select interface="popover" aria-label="Food" placeholder="Select food">
  <ion-select-option value="apples">Apples</ion-select-option>
  <ion-select-option value="oranges">Oranges</ion-select-option>
  <ion-select-option value="bananas">Bananas</ion-select-option>
</ion-select>

src/app/example.component.ts

import { Component } from '@angular/core';
import { IonSelect, IonSelectOption } from '@ionic/angular';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonSelect, IonSelectOption],
})
export class ExampleComponent {}

React

import React from 'react';
import { IonSelect, IonSelectOption } from '@ionic/react';

function Example() {
  return (
    <IonSelect interface="popover" aria-label="Food" placeholder="Select food">
      <IonSelectOption value="apples">Apples</IonSelectOption>
      <IonSelectOption value="oranges">Oranges</IonSelectOption>
      <IonSelectOption value="bananas">Bananas</IonSelectOption>
    </IonSelect>
  );
}
export default Example;

Vue

<template>
  <ion-select interface="popover" aria-label="Food" placeholder="Select food">
    <ion-select-option value="apples">Apples</ion-select-option>
    <ion-select-option value="oranges">Oranges</ion-select-option>
    <ion-select-option value="bananas">Bananas</ion-select-option>
  </ion-select>
</template>

<script setup lang="ts">
  import { IonSelect, IonSelectOption } from '@ionic/vue';
</script>

JavaScript

index.html

<ion-select interface="modal" aria-label="Food" placeholder="Select food">
  <ion-select-option value="apples">Apples</ion-select-option>
  <ion-select-option value="oranges">Oranges</ion-select-option>
  <ion-select-option value="bananas">Bananas</ion-select-option>
</ion-select>

Angular

src/app/example.component.html

<ion-select interface="modal" aria-label="Food" placeholder="Select food">
  <ion-select-option value="apples">Apples</ion-select-option>
  <ion-select-option value="oranges">Oranges</ion-select-option>
  <ion-select-option value="bananas">Bananas</ion-select-option>
</ion-select>

src/app/example.component.ts

import { Component } from '@angular/core';
import { IonSelect, IonSelectOption } from '@ionic/angular';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonSelect, IonSelectOption],
})
export class ExampleComponent {}

React

import React from 'react';
import { IonSelect, IonSelectOption } from '@ionic/react';

function Example() {
  return (
    <IonSelect interface="modal" aria-label="Food" placeholder="Select food">
      <IonSelectOption value="apples">Apples</IonSelectOption>
      <IonSelectOption value="oranges">Oranges</IonSelectOption>
      <IonSelectOption value="bananas">Bananas</IonSelectOption>
    </IonSelect>
  );
}
export default Example;

Vue

<template>
  <ion-select interface="modal" aria-label="Food" placeholder="Select food">
    <ion-select-option value="apples">Apples</ion-select-option>
    <ion-select-option value="oranges">Oranges</ion-select-option>
    <ion-select-option value="bananas">Bananas</ion-select-option>
  </ion-select>
</template>

<script setup lang="ts">
  import { IonSelect, IonSelectOption } from '@ionic/vue';
</script>

Responding to Interaction

select와의 사용자 상호작용을 처리하는 주요 방법은 ionChange, ionDismiss, ionCancel 이벤트예요. 이 이벤트들과 select가 발생시키는 다른 이벤트에 대한 자세한 내용은 Events를 참고해 주세요.

JavaScript

index.html

<ion-list>
  <ion-item>
    <ion-select aria-label="Food" placeholder="Select food">
      <ion-select-option value="apples">Apples</ion-select-option>
      <ion-select-option value="oranges">Oranges</ion-select-option>
      <ion-select-option value="bananas">Bananas</ion-select-option>
    </ion-select>
  </ion-item>
</ion-list>

<script>
  const select = document.querySelector('ion-select');
  select.addEventListener('ionChange', ({ detail }) => {
    console.log('ionChange emitted with value:', detail.value);
  });
  select.addEventListener('ionDismiss', () => {
    console.log('ionDismiss emitted');
  });
  select.addEventListener('ionCancel', ({ detail }) => {
    console.log('ionCancel emitted with value:', detail.value);
  });
</script>

Angular

src/app/example.component.html

<ion-list>
  <ion-item>
    <ion-select aria-label="Food" placeholder="Select food" (ionChange)="handleChange($event)">
      <ion-select-option value="apples">Apples</ion-select-option>
      <ion-select-option value="oranges">Oranges</ion-select-option>
      <ion-select-option value="bananas">Bananas</ion-select-option>
    </ion-select>
  </ion-item>
</ion-list>

src/app/example.component.ts

import { Component } from '@angular/core';
import { IonItem, IonSelect, IonSelectOption } from '@ionic/angular';
import { SelectCustomEvent } from '@ionic/angular';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonItem, IonList, IonSelect, IonSelectOption],
})
export class ExampleComponent {
  handleChange(event: Event) {
    console.log('ionChange emitted with value:', (event as SelectCustomEvent).detail.value);
  }
}

React

import React from 'react';
import { IonItem, IonList, IonSelect, IonSelectOption, SelectCustomEvent } from '@ionic/react';

function Example() {
  const handleChange = (event: SelectCustomEvent) => {
    console.log('ionChange emitted with value:', event.detail.value);
  };
  return (
    <IonList>
      <IonItem>
        <IonSelect aria-label="Food" placeholder="Select food" onIonChange={handleChange}>
          <IonSelectOption value="apples">Apples</IonSelectOption>
          <IonSelectOption value="oranges">Oranges</IonSelectOption>
          <IonSelectOption value="bananas">Bananas</IonSelectOption>
        </IonSelect>
      </IonItem>
    </IonList>
  );
}
export default Example;

Vue

<template>
  <ion-list>
    <ion-item>
      <ion-select aria-label="Food" placeholder="Select food" @ionChange="handleChange">
        <ion-select-option value="apples">Apples</ion-select-option>
        <ion-select-option value="oranges">Oranges</ion-select-option>
        <ion-select-option value="bananas">Bananas</ion-select-option>
      </ion-select>
    </ion-item>
  </ion-list>
</template>

<script setup lang="ts">
  import { IonItem, IonSelect, IonSelectOption } from '@ionic/vue';

  const handleChange = (event: CustomEvent) => {
    console.log('ionChange emitted with value:', event.detail.value);
  };
</script>

Object Value References

select 값에 객체를 사용하는 경우, 서버나 데이터베이스에서 객체의 정체성(identity)이 바뀌는 일이 생길 수 있어요. 반면 선택된 값의 정체성은 그대로 유지되죠. 예를 들어 원하는 객체 값을 가진 기존 레코드가 select에 로드되었는데, 새로 가져온 select 옵션들이 서로 다른 정체성을 갖게 되는 경우가 있어요. 이렇게 되면 원래 선택이 그대로 남아 있음에도 select가 값이 전혀 없는 것처럼 보일 수 있어요.

기본적으로 select는 엄격한 동등성(===)을 사용해 옵션이 선택되었는지 판단해요. compareWith 속성에 속성 이름이나 함수를 제공하면 이 동작을 재정의할 수 있어요.

Using compareWith

JavaScript

index.html

<ion-list>
  <ion-item>
    <ion-select aria-label="Food" [compareWith]="compareWith" placeholder="Select food">
      <ion-select-option [value]="{ id: 1, name: 'Apples' }">Apples</ion-select-option>
      <ion-select-option [value]="{ id: 2, name: 'Oranges' }">Oranges</ion-select-option>
      <ion-select-option [value]="{ id: 3, name: 'Bananas' }">Bananas</ion-select-option>
    </ion-select>
  </ion-item>
</ion-list>

Angular

src/app/example.component.html

<ion-list>
  <ion-item>
    <ion-select aria-label="Food" [compareWith]="compareWith" placeholder="Select food">
      <ion-select-option [value]="{ id: 1, name: 'Apples' }">Apples</ion-select-option>
      <ion-select-option [value]="{ id: 2, name: 'Oranges' }">Oranges</ion-select-option>
      <ion-select-option [value]="{ id: 3, name: 'Bananas' }">Bananas</ion-select-option>
    </ion-select>
  </ion-item>
</ion-list>

src/app/example.component.ts

import { Component } from '@angular/core';
import { IonItem, IonList, IonSelect, IonSelectOption } from '@ionic/angular';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonItem, IonList, IonSelect, IonSelectOption],
})
export class ExampleComponent {
  compareWith(o1: any, o2: any) {
    return o1 && o2 ? o1.id === o2.id : o1 === o2;
  }
}

React

import React from 'react';
import { IonItem, IonList, IonSelect, IonSelectOption } from '@ionic/react';

function Example() {
  const compareWith = (o1: any, o2: any) => {
    return o1 && o2 ? o1.id === o2.id : o1 === o2;
  };
  return (
    <IonList>
      <IonItem>
        <IonSelect aria-label="Food" compareWith={compareWith} placeholder="Select food">
          <IonSelectOption value={{ id: 1, name: 'Apples' }}>Apples</IonSelectOption>
          <IonSelectOption value={{ id: 2, name: 'Oranges' }}>Oranges</IonSelectOption>
          <IonSelectOption value={{ id: 3, name: 'Bananas' }}>Bananas</IonSelectOption>
        </IonSelect>
      </IonItem>
    </IonList>
  );
}
export default Example;

Vue

<template>
  <ion-list>
    <ion-item>
      <ion-select aria-label="Food" :compare-with="compareWith" placeholder="Select food">
        <ion-select-option :value="{ id: 1, name: 'Apples' }">Apples</ion-select-option>
        <ion-select-option :value="{ id: 2, name: 'Oranges' }">Oranges</ion-select-option>
        <ion-select-option :value="{ id: 3, name: 'Bananas' }">Bananas</ion-select-option>
      </ion-select>
    </ion-item>
  </ion-list>
</template>

<script setup lang="ts">
  import { IonItem, IonSelect, IonSelectOption } from '@ionic/vue';

  const compareWith = (o1: any, o2: any) => {
    return o1 && o2 ? o1.id === o2.id : o1 === o2;
  };
</script>

Filled Selects

Material Design은 select의 채워진(filled) 스타일을 제공해요. select의 fill 속성을 "solid" 또는 "outline"으로 설정할 수 있어요.

채워진 select는 select의 mode를 md로 설정하면 iOS에서도 사용할 수 있어요.

Warning

fill을 사용하는 select는 컴포넌트 간 스타일 충돌 때문에 ion-item 안에서 사용하면 안 돼요.

JavaScript

<ion-select label="Solid select" label-placement="floating" fill="solid">
  <ion-select-option value="apple">Apple</ion-select-option>
  <ion-select-option value="banana">Banana</ion-select-option>
  <ion-select-option value="orange">Orange</ion-select-option>
</ion-select>

<br />

<ion-select label="Outline select" label-placement="floating" fill="outline">
  <ion-select-option value="apple">Apple</ion-select-option>
  <ion-select-option value="banana">Banana</ion-select-option>
  <ion-select-option value="orange">Orange</ion-select-option>
</ion-select>

Angular

src/app/example.component.html

<ion-select label="Solid select" label-placement="floating" fill="solid">
  <ion-select-option value="apple">Apple</ion-select-option>
  <ion-select-option value="banana">Banana</ion-select-option>
  <ion-select-option value="orange">Orange</ion-select-option>
</ion-select>

<br />

<ion-select label="Outline select" label-placement="floating" fill="outline">
  <ion-select-option value="apple">Apple</ion-select-option>
  <ion-select-option value="banana">Banana</ion-select-option>
  <ion-select-option value="orange">Orange</ion-select-option>
</ion-select>

src/app/example.component.ts

import { Component } from '@angular/core';
import { IonSelect, IonSelectOption } from '@ionic/angular';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonSelect, IonSelectOption],
})
export class ExampleComponent {}

React

import React from 'react';
import { IonSelect, IonSelectOption } from '@ionic/react';

function Example() {
  return (
    <>
      <IonSelect label="Solid select" labelPlacement="floating" fill="solid">
        <IonSelectOption value="apple">Apple</IonSelectOption>
        <IonSelectOption value="banana">Banana</IonSelectOption>
        <IonSelectOption value="orange">Orange</IonSelectOption>
      </IonSelect>

      <br />

      <IonSelect label="Outline select" labelPlacement="floating" fill="outline">
        <IonSelectOption value="apple">Apple</IonSelectOption>
        <IonSelectOption value="banana">Banana</IonSelectOption>
        <IonSelectOption value="orange">Orange</IonSelectOption>
      </IonSelect>
    </>
  );
}
export default Example;

Vue

<template>
  <ion-select label="Solid select" label-placement="floating" fill="solid">
    <ion-select-option value="apple">Apple</ion-select-option>
    <ion-select-option value="banana">Banana</ion-select-option>
    <ion-select-option value="orange">Orange</ion-select-option>
  </ion-select>

  <br />

  <ion-select label="Outline select" label-placement="floating" fill="outline">
    <ion-select-option value="apple">Apple</ion-select-option>
    <ion-select-option value="banana">Banana</ion-select-option>
    <ion-select-option value="orange">Orange</ion-select-option>
  </ion-select>
</template>

<script setup lang="ts">
  import { IonSelect, IonSelectOption } from '@ionic/vue';
</script>

Select Buttons

알럿은 Cancel과 OK 두 개의 버튼을 지원해요. 각 버튼의 텍스트는 cancelText와 okText 속성을 사용해 커스터마이즈할 수 있어요.

action-sheet와 popover 인터페이스에는 OK 버튼이 없어요. 옵션 중 하나를 클릭하면 자동으로 오버레이가 닫히고 해당 값을 선택해요. popover 인터페이스에는 Cancel 버튼이 없고, 배경을 클릭하면 오버레이가 닫혀요.

modal 인터페이스에는 헤더에 Close 버튼이 하나 있어요. 이 버튼은 모달을 닫는 역할만 해요. 이 버튼을 클릭하거나 다른 방법으로 모달을 닫아도 선택한 값은 유지돼요.

JavaScript

<ion-list>
  <ion-item>
    <ion-select label="Alert Interface" placeholder="Select fruit" ok-text="Choose Fruit" cancel-text="Cancel Choice">
      <ion-select-option value="apples">Apples</ion-select-option>
      <ion-select-option value="oranges">Oranges</ion-select-option>
      <ion-select-option value="bananas">Bananas</ion-select-option>
    </ion-select>
  </ion-item>
  <ion-item>
    <ion-select
      label="Action Sheet Interface"
      interface="action-sheet"
      placeholder="Select fruit"
      cancel-text="Cancel Choice"
    >
      <ion-select-option value="apples">Apples</ion-select-option>
      <ion-select-option value="oranges">Oranges</ion-select-option>
      <ion-select-option value="bananas">Bananas</ion-select-option>
    </ion-select>
  </ion-item>
</ion-list>

Angular

src/app/example.component.html

<ion-list>
  <ion-item>
    <ion-select label="Alert Interface" placeholder="Select fruit" okText="Choose Fruit" cancelText="Cancel Choice">
      <ion-select-option value="apples">Apples</ion-select-option>
      <ion-select-option value="oranges">Oranges</ion-select-option>
      <ion-select-option value="bananas">Bananas</ion-select-option>
    </ion-select>
  </ion-item>
  <ion-item>
    <ion-select
      label="Action Sheet Interface"
      interface="action-sheet"
      placeholder="Select fruit"
      cancelText="Cancel Choice"
    >
      <ion-select-option value="apples">Apples</ion-select-option>
      <ion-select-option value="oranges">Oranges</ion-select-option>
      <ion-select-option value="bananas">Bananas</ion-select-option>
    </ion-select>
  </ion-item>
</ion-list>

src/app/example.component.ts

import { Component } from '@angular/core';
import { IonItem, IonList, IonSelect, IonSelectOption } from '@ionic/angular';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonItem, IonList, IonSelect, IonSelectOption],
})
export class ExampleComponent {}

React

import React from 'react';
import { IonItem, IonLabel, IonList, IonSelect, IonSelectOption } from '@ionic/react';
function Example() {
  return (
    <IonList>
      <IonItem>
        <IonSelect label="Alert Interface" placeholder="Select fruit" okText="Choose Fruit" cancelText="Cancel Choice">
          <IonSelectOption value="apples">Apples</IonSelectOption>
          <IonSelectOption value="oranges">Oranges</IonSelectOption>
          <IonSelectOption value="bananas">Bananas</IonSelectOption>
        </IonSelect>
      </IonItem>
      <IonItem>
        <IonSelect
          label="Action Sheet Interface"
          interface="action-sheet"
          placeholder="Select fruit"
          cancelText="Cancel Choice"
        >
          <IonSelectOption value="apples">Apples</IonSelectOption>
          <IonSelectOption value="oranges">Oranges</IonSelectOption>
          <IonSelectOption value="bananas">Bananas</IonSelectOption>
        </IonSelect>
      </IonItem>
    </IonList>
  );
}
export default Example;

Vue

<template>
  <ion-list>
    <ion-item>
      <ion-select label="Alert Interface" placeholder="Select fruit" ok-text="Choose Fruit" cancel-text="Cancel Choice">
        <ion-select-option value="apples">Apples</ion-select-option>
        <ion-select-option value="oranges">Oranges</ion-select-option>
        <ion-select-option value="bananas">Bananas</ion-select-option>
      </ion-select>
    </ion-item>
    <ion-item>
      <ion-select
        label="Action Sheet Interface"
        interface="action-sheet"
        placeholder="Select fruit"
        cancel-text="Cancel Choice"
      >
        <ion-select-option value="apples">Apples</ion-select-option>
        <ion-select-option value="oranges">Oranges</ion-select-option>
        <ion-select-option value="bananas">Bananas</ion-select-option>
      </ion-select>
    </ion-item>
  </ion-list>
</template>

<script setup lang="ts">
  import { IonItem, IonLabel, IonList, IonSelect, IonSelectOption } from '@ionic/vue';
</script>

Interface Options

select는 alert, action sheet, popover, modal 인터페이스를 사용하기 때문에 interfaceOptions 속성을 통해 이 컴포넌트들에 옵션을 전달할 수 있어요. 커스텀 헤더, 서브헤더, css class 등을 전달하는 데 사용할 수 있어요.

각 인터페이스가 받는 속성은 ion-alert docs, ion-action-sheet docs, ion-popover docs, ion-modal docs를 참고해 주세요.

Note: interfaceOptions는 alert 인터페이스의 inputs나 buttons를 재정의하지 않아요.

JavaScript

<ion-list>
  <ion-item>
    <ion-select label="Alert" id="customAlertSelect" interface="alert" placeholder="Select One">
      <ion-select-option value="bacon">Bacon</ion-select-option>
      <ion-select-option value="onions">Onions</ion-select-option>
      <ion-select-option value="pepperoni">Pepperoni</ion-select-option>
    </ion-select>
  </ion-item>

  <ion-item>
    <ion-select label="Popover" id="customPopoverSelect" interface="popover" placeholder="Select One">
      <ion-select-option value="brown">Brown</ion-select-option>
      <ion-select-option value="blonde">Blonde</ion-select-option>
      <ion-select-option value="red">Red</ion-select-option>
    </ion-select>
  </ion-item>

  <ion-item>
    <ion-select label="Action Sheet" id="customActionSheetSelect" interface="action-sheet" placeholder="Select One">
      <ion-select-option value="red">Red</ion-select-option>
      <ion-select-option value="green">Green</ion-select-option>
      <ion-select-option value="blue">Blue</ion-select-option>
    </ion-select>
  </ion-item>

  <ion-item>
    <ion-select label="Modal" id="customModalSelect" interface="modal" placeholder="Select One">
      <ion-select-option value="reese's">Reese's</ion-select-option>
      <ion-select-option value="snickers">Snickers</ion-select-option>
      <ion-select-option value="twix">Twix</ion-select-option>
    </ion-select>
  </ion-item>
</ion-list>

<script>
  const customAlertSelect = document.getElementById('customAlertSelect');
  const customAlertOptions = {
    header: 'Pizza Toppings',
    subHeader: 'Select your favorite topping',
    message: 'Choose only one',
    translucent: true,
  };
  customAlertSelect.interfaceOptions = customAlertOptions;

  const customPopoverSelect = document.getElementById('customPopoverSelect');
  const customPopoverOptions = {
    header: 'Hair Color',
    subHeader: 'Select your hair color',
    message: 'Only select your dominant hair color',
  };
  customPopoverSelect.interfaceOptions = customPopoverOptions;

  const customActionSheetSelect = document.getElementById('customActionSheetSelect');
  const customActionSheetOptions = {
    header: 'Colors',
    subHeader: 'Select your favorite color',
  };
  customActionSheetSelect.interfaceOptions = customActionSheetOptions;

  const customModalSelect = document.getElementById('customModalSelect');
  const customModalOptions = {
    header: 'Favorite Candy',
    breakpoints: [0, 0.5],
    initialBreakpoint: 0.5,
  };
  customModalSelect.interfaceOptions = customModalOptions;
</script>

Angular

src/app/example.component.html

<ion-list>
  <ion-item>
    <ion-select label="Alert" [interfaceOptions]="customAlertOptions" interface="alert" placeholder="Select One">
      <ion-select-option value="bacon">Bacon</ion-select-option>
      <ion-select-option value="onions">Onions</ion-select-option>
      <ion-select-option value="pepperoni">Pepperoni</ion-select-option>
    </ion-select>
  </ion-item>

  <ion-item>
    <ion-select label="Popover" [interfaceOptions]="customPopoverOptions" interface="popover" placeholder="Select One">
      <ion-select-option value="brown">Brown</ion-select-option>
      <ion-select-option value="blonde">Blonde</ion-select-option>
      <ion-select-option value="red">Red</ion-select-option>
    </ion-select>
  </ion-item>

  <ion-item>
    <ion-select
      label="Action Sheet"
      [interfaceOptions]="customActionSheetOptions"
      interface="action-sheet"
      placeholder="Select One"
    >
      <ion-select-option value="red">Red</ion-select-option>
      <ion-select-option value="green">Green</ion-select-option>
      <ion-select-option value="blue">Blue</ion-select-option>
    </ion-select>
  </ion-item>

  <ion-item>
    <ion-select label="Modal" [interfaceOptions]="customModalOptions" interface="modal" placeholder="Select One">
      <ion-select-option value="reese's">Reese's</ion-select-option>
      <ion-select-option value="snickers">Snickers</ion-select-option>
      <ion-select-option value="twix">Twix</ion-select-option>
    </ion-select>
  </ion-item>
</ion-list>

src/app/example.component.ts

import { Component } from '@angular/core';
import { IonItem, IonList, IonSelect, IonSelectOption } from '@ionic/angular';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonItem, IonList, IonSelect, IonSelectOption],
})
export class ExampleComponent {
  customAlertOptions = {
    header: 'Pizza Toppings',
    subHeader: 'Select your favorite topping',
    message: 'Choose only one',
    translucent: true,
  };

  customPopoverOptions = {
    header: 'Hair Color',
    subHeader: 'Select your hair color',
    message: 'Only select your dominant hair color',
  };

  customActionSheetOptions = {
    header: 'Colors',
    subHeader: 'Select your favorite color',
  };

  customModalOptions = {
    header: 'Favorite Candy',
    breakpoints: [0, 0.5],
    initialBreakpoint: 0.5,
  };
}

React

import React from 'react';
import { IonItem, IonLabel, IonList, IonSelect, IonSelectOption } from '@ionic/react';
function Example() {
  const customAlertOptions = {
    header: 'Pizza Toppings',
    subHeader: 'Select your favorite topping',
    message: 'Choose only one',
    translucent: true,
  };

  const customPopoverOptions = {
    header: 'Hair Color',
    subHeader: 'Select your hair color',
    message: 'Only select your dominant hair color',
  };

  const customActionSheetOptions = {
    header: 'Colors',
    subHeader: 'Select your favorite color',
  };

  const customModalOptions = {
    header: 'Favorite Candy',
    breakpoints: [0, 0.5],
    initialBreakpoint: 0.5,
  };

  return (
    <IonList>
      <IonItem>
        <IonSelect label="Alert" interfaceOptions={customAlertOptions} interface="alert" placeholder="Select One">
          <IonSelectOption value="bacon">Bacon</IonSelectOption>
          <IonSelectOption value="onions">Onions</IonSelectOption>
          <IonSelectOption value="pepperoni">Pepperoni</IonSelectOption>
        </IonSelect>
      </IonItem>

      <IonItem>
        <IonSelect label="Popover" interfaceOptions={customPopoverOptions} interface="popover" placeholder="Select One">
          <IonSelectOption value="brown">Brown</IonSelectOption>
          <IonSelectOption value="blonde">Blonde</IonSelectOption>
          <IonSelectOption value="red">Red</IonSelectOption>
        </IonSelect>
      </IonItem>

      <IonItem>
        <IonSelect
          label="Action Sheet"
          interfaceOptions={customActionSheetOptions}
          interface="action-sheet"
          placeholder="Select One"
        >
          <IonSelectOption value="red">Red</IonSelectOption>
          <IonSelectOption value="green">Green</IonSelectOption>
          <IonSelectOption value="blue">Blue</IonSelectOption>
        </IonSelect>
      </IonItem>

      <IonItem>
        <IonSelect label="Modal" interfaceOptions={customModalOptions} interface="modal" placeholder="Select One">
          <IonSelectOption value="reese's">Reese's</IonSelectOption>
          <IonSelectOption value="snickers">Snickers</IonSelectOption>
          <IonSelectOption value="twix">Twix</IonSelectOption>
        </IonSelect>
      </IonItem>
    </IonList>
  );
}
export default Example;

Vue

<template>
  <ion-list>
    <ion-item>
      <ion-select label="Alert" :interface-options="customAlertOptions" interface="alert" placeholder="Select One">
        <ion-select-option value="bacon">Bacon</ion-select-option>
        <ion-select-option value="onions">Onions</ion-select-option>
        <ion-select-option value="pepperoni">Pepperoni</ion-select-option>
      </ion-select>
    </ion-item>

    <ion-item>
      <ion-select
        label="Popover"
        :interface-options="customPopoverOptions"
        interface="popover"
        placeholder="Select One"
      >
        <ion-select-option value="brown">Brown</ion-select-option>
        <ion-select-option value="blonde">Blonde</ion-select-option>
        <ion-select-option value="red">Red</ion-select-option>
      </ion-select>
    </ion-item>

    <ion-item>
      <ion-select
        label="Action Sheet"
        :interface-options="customActionSheetOptions"
        interface="action-sheet"
        placeholder="Select One"
      >
        <ion-select-option value="red">Red</ion-select-option>
        <ion-select-option value="green">Green</ion-select-option>
        <ion-select-option value="blue">Blue</ion-select-option>
      </ion-select>
    </ion-item>

    <ion-item>
      <ion-select label="Modal" :interface-options="customModalOptions" interface="modal" placeholder="Select One">
        <ion-select-option value="reese's">Reese's</ion-select-option>
        <ion-select-option value="snickers">Snickers</ion-select-option>
        <ion-select-option value="twix">Twix</ion-select-option>
      </ion-select>
    </ion-item>
  </ion-list>
</template>

<script setup lang="ts">
  import { IonItem, IonLabel, IonList, IonSelect, IonSelectOption } from '@ionic/vue';

  const customAlertOptions = {
    header: 'Pizza Toppings',
    subHeader: 'Select your favorite topping',
    message: 'Choose only one',
    translucent: true,
  };

  const customPopoverOptions = {
    header: 'Hair Color',
    subHeader: 'Select your hair color',
    message: 'Only select your dominant hair color',
  };

  const customActionSheetOptions = {
    header: 'Colors',
    subHeader: 'Select your favorite color',
  };

  const customModalOptions = {
    header: 'Favorite Candy',
    breakpoints: [0, 0.5],
    initialBreakpoint: 0.5,
  };
</script>

Start and End Slots

start와 end 슬롯은 select의 양쪽에 아이콘, 버튼 또는 접두사/접미사 텍스트를 배치하는 데 사용할 수 있어요. 슬롯 콘텐츠를 클릭하면 select가 열리지 않아요.

Note

대부분의 경우 이 슬롯에 배치되는 Icon 컴포넌트에는 aria-hidden="true"를 설정해야 해요. 자세한 내용은 Icon accessibility docs를 참고해 주세요. 슬롯 콘텐츠와 상호작용해야 한다면 Button 같은 인터랙티브 요소로 감싸야 해요. 그래야 콘텐츠를 탭으로 이동할 수 있어요.

JavaScript

index.html

<ion-list>
  <ion-item>
    <ion-select label-placement="stacked" label="Favorite fruit" value="apple">
      <ion-icon slot="start" name="leaf" aria-hidden="true"></ion-icon>
      <ion-select-option value="apple">Apple</ion-select-option>
      <ion-select-option value="banana">Banana</ion-select-option>
      <ion-select-option value="orange">Orange</ion-select-option>
      <ion-button fill="clear" slot="end" aria-label="Show/hide password">
        <ion-icon slot="icon-only" name="eye" aria-hidden="true"></ion-icon>
      </ion-button>
    </ion-select>
  </ion-item>
</ion-list>

index.ts

import { defineCustomElements } from '@ionic/core/loader';

import { addIcons } from 'ionicons';
import { eye, leaf } from 'ionicons/icons';

/* Core CSS required for Ionic components to work properly */
import '@ionic/core/css/core.css';

/* Basic CSS for apps built with Ionic */
import '@ionic/core/css/normalize.css';
import '@ionic/core/css/structure.css';
import '@ionic/core/css/typography.css';

/* Optional CSS utils that can be commented out */
import '@ionic/core/css/padding.css';
import '@ionic/core/css/float-elements.css';
import '@ionic/core/css/text-alignment.css';
import '@ionic/core/css/text-transformation.css';
import '@ionic/core/css/flex-utils.css';
import '@ionic/core/css/display.css';

/**
 * Ionic Dark Palette
 * -----------------------------------------------------
 * For more information, please see:
 * https://ionicframework.com/docs/theming/dark-mode
 */

// import '@ionic/core/css/palettes/dark.always.css';
// import '@ionic/core/css/palettes/dark.class.css';
import '@ionic/core/css/palettes/dark.system.css';

/* Theme variables */
import './theme/variables.css';

/**
 * On Ionicons 7.2+ these icons
 * get mapped to a kebab-case key.
 * Alternatively, developers can do:
 * addIcons({ 'eye': eye, 'leaf': leaf });
 */
addIcons({ eye, leaf });

defineCustomElements();

Angular

src/app/example.component.html

<ion-list>
  <ion-item>
    <ion-select labelPlacement="stacked" label="Favorite fruit" value="apple">
      <ion-icon slot="start" name="leaf" aria-hidden="true"></ion-icon>
      <ion-select-option value="apple">Apple</ion-select-option>
      <ion-select-option value="banana">Banana</ion-select-option>
      <ion-select-option value="orange">Orange</ion-select-option>
      <ion-button fill="clear" slot="end" aria-label="Show/hide password">
        <ion-icon slot="icon-only" name="eye" aria-hidden="true"></ion-icon>
      </ion-button>
    </ion-select>
  </ion-item>
</ion-list>

src/app/example.component.ts

import { Component } from '@angular/core';
import { IonButton, IonIcon, IonItem, IonList, IonSelect, IonSelectOption } from '@ionic/angular';

import { addIcons } from 'ionicons';
import { eye, leaf } from 'ionicons/icons';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonButton, IonIcon, IonItem, IonList, IonSelect, IonSelectOption],
})
export class ExampleComponent {
  constructor() {
    /**
     * Any icons you want to use in your application
     * can be registered in app.component.ts and then
     * referenced by name anywhere in your application.
     */
    addIcons({ eye, leaf });
  }
}

React

import React from 'react';
import { IonButton, IonIcon, IonItem, IonList, IonSelect, IonSelectOption } from '@ionic/react';
import { eye, leaf } from 'ionicons/icons';

function Example() {
  return (
    <IonList>
      <IonItem>
        <IonSelect labelPlacement="stacked" label="Favorite fruit" value="apple">
          <IonIcon slot="start" icon={leaf} aria-hidden="true"></IonIcon>
          <IonSelectOption value="apple">Apple</IonSelectOption>
          <IonSelectOption value="banana">Banana</IonSelectOption>
          <IonSelectOption value="orange">Orange</IonSelectOption>
          <IonButton fill="clear" slot="end" aria-label="Show/hide password">
            <IonIcon slot="icon-only" icon={eye} aria-hidden="true"></IonIcon>
          </IonButton>
        </IonSelect>
      </IonItem>
    </IonList>
  );
}
export default Example;

Vue

<template>
  <ion-list>
    <ion-item>
      <ion-select label-placement="stacked" label="Favorite fruit" value="apple">
        <ion-icon slot="start" :icon="leaf" aria-hidden="true"></ion-icon>
        <ion-select-option value="apple">Apple</ion-select-option>
        <ion-select-option value="banana">Banana</ion-select-option>
        <ion-select-option value="orange">Orange</ion-select-option>
        <ion-button fill="clear" slot="end" aria-label="Show/hide password">
          <ion-icon slot="icon-only" :icon="eye" aria-hidden="true"></ion-icon>
        </ion-button>
      </ion-select>
    </ion-item>
  </ion-list>
</template>

<script setup lang="ts">
  import { IonButton, IonIcon, IonItem, IonList, IonSelect, IonSelectOption } from '@ionic/vue';
  import { eye, leaf } from 'ionicons/icons';
</script>

Rich Content Options

Important

select 옵션의 리치 콘텐츠(rich content)는 기본적으로 비활성화되어 있어요. global Ionic config에서 innerHTMLTemplatesEnabled를 true로 설정해야 해요. 비활성화되어 있으면 옵션 내부의 마크업은 일반 텍스트로 처리돼요. 커스텀 HTML을 활성화할 때는 Security에서 살균(sanitization) 지침을 참고해 주세요.

단일 텍스트 라벨 외에도 Select Options는 select 인터페이스에 HTML 리치 콘텐츠를 포함할 수 있어요. 이름이 붙은 슬롯 없이 옵션 안에 추가한 요소는 기본 슬롯으로 들어가요. start와 end 슬롯은 기본 슬롯 양쪽에 요소를 배치해요. description 속성은 라벨 아래에 표시되는 추가 지원 텍스트를 제공하는 데 사용할 수 있어요.

이것은 닫힌 필드를 장식하는 ion-select의 Start and End Slots과는 별개예요. 리치 콘텐츠 옵션은 select를 연 후 인터페이스에 표시돼요.

옵션이 선택되면 닫힌 필드에는 옵션의 텍스트 콘텐츠만 일반 텍스트로 표시돼요. HTML 마크업은 제거되고, start와 end 슬롯 및 description 속성은 선택된 표시에 포함되지 않아요.

JavaScript

index.html

<script>
  /**
   * `innerHTMLTemplatesEnabled` must be enabled for rich-content
   * select options to render correctly.
   */
  window.Ionic = {
    config: {
      innerHTMLTemplatesEnabled: true,
    },
  };
</script>

<ion-list>
  <!-- Dynamically created Select components will be added here -->
</ion-list>

<style>
  /* -----------------------------------------------------*/
  /* These styles are for demonstration purposes only.    */
  /* They are not required for the rich options to work.  */
  /* -----------------------------------------------------*/

  /**
  * All Interfaces
  * ------------------------------------------------
  * Override the flex styles so that the title and
  * subtitle stack vertically.
  */
  .select-option-content div.alert-radio-label-text,
  .select-option-content span.action-sheet-button-label-text,
  .select-option-content div.select-option-label-text {
    flex-direction: column;
    align-items: start;
    gap: 5px;
  }

  /* Action Sheet Interface */
  ion-action-sheet .select-option-description {
    text-align: start;
  }

  /* Alert Interface */
  ion-alert.select-alert {
    --min-width: 350px;
  }

  /* Modal, Popover Interfaces */
  ion-popover.select-popover ion-list ion-radio.in-item::part(label),
  ion-modal.select-modal ion-list ion-radio.in-item::part(label) {
    margin-top: 10px;
    margin-bottom: 10px;
  }

  /* Custom Select Option Title */
  .select-option-content .option-title {
    font-size: 1rem;
    font-weight: 600;
  }

  /* Custom Select Option Subtitle */
  .select-option-content .option-subtitle {
    font-size: 0.8125rem;
    font-weight: 500;
  }
</style>

<script>
  /* Helper function to format the interface label */
  const formatInterfaceLabel = (selectInterface) => {
    return selectInterface
      .split('-')
      .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
      .join(' ');
  };

  /* Dynamically create the different Select components */
  const selectInterfaces = ['alert', 'action-sheet', 'modal', 'popover'];

  selectInterfaces.forEach((selectInterface) => {
    const list = document.querySelector('ion-list');
    const item = document.createElement('ion-item');
    const select = document.createElement('ion-select');
    select.label = formatInterfaceLabel(selectInterface);
    select.placeholder = 'Select one';
    select.interface = selectInterface;

    const optionsHTML = `
      <ion-select-option value="airplane" description="Carry-on · Window seat">
        <ion-icon slot="start" size="large" aria-hidden="true" name="airplane"></ion-icon>
        <span class="option-title">Flight</span>
        <span class="option-subtitle">2h 15m · Nonstop</span>
        <ion-badge slot="end" color="tertiary">$279</ion-badge>
      </ion-select-option>
      <ion-select-option value="bus" description="Bike rack · Wi-Fi">
        <ion-icon slot="start" size="large" aria-hidden="true" name="bus"></ion-icon>
        <span class="option-title">Bus</span>
        <span class="option-subtitle">6h 40m · 1 transfer</span>
        <ion-badge slot="end" color="tertiary">$39</ion-badge>
      </ion-select-option>
      <ion-select-option value="car" description="Unlimited miles · GPS">
        <ion-icon slot="start" size="large" aria-hidden="true" name="car"></ion-icon>
        <span class="option-title">Rental Car</span>
        <span class="option-subtitle">5h 10m · Flexible route</span>
        <ion-badge slot="end" color="tertiary">$92</ion-badge>
      </ion-select-option>
      <ion-select-option value="train" description="Reserved seat · Wi-Fi">
        <ion-icon slot="start" size="large" aria-hidden="true" name="train"></ion-icon>
        <span class="option-title">Train</span>
        <span class="option-subtitle">4h 55m · Direct</span>
        <ion-badge slot="end" color="tertiary">$64</ion-badge>
      </ion-select-option>
    `;
    select.innerHTML = optionsHTML;

    /* The interfaceOptions property is for demonstration purposes only. */
    /* It is not required for the rich options to work. */
    select.interfaceOptions = {
      header: 'Travel mode',
    };

    item.appendChild(select);
    list.appendChild(item);
  });
</script>

index.ts

import { defineCustomElements } from '@ionic/core/loader';

import { addIcons } from 'ionicons';
import { airplane, bus, car, train } from 'ionicons/icons';

/* Core CSS required for Ionic components to work properly */
import '@ionic/core/css/core.css';

/* Basic CSS for apps built with Ionic */
import '@ionic/core/css/normalize.css';
import '@ionic/core/css/structure.css';
import '@ionic/core/css/typography.css';

/* Optional CSS utils that can be commented out */
import '@ionic/core/css/padding.css';
import '@ionic/core/css/float-elements.css';
import '@ionic/core/css/text-alignment.css';
import '@ionic/core/css/text-transformation.css';
import '@ionic/core/css/flex-utils.css';
import '@ionic/core/css/display.css';

/**
 * Ionic Dark Palette
 * -----------------------------------------------------
 * For more information, please see:
 * https://ionicframework.com/docs/theming/dark-mode
 */

// import '@ionic/core/css/palettes/dark.always.css';
// import '@ionic/core/css/palettes/dark.class.css';
import '@ionic/core/css/palettes/dark.system.css';

/* Theme variables */
import './theme/variables.css';

/**
 * On Ionicons 7.2+ these icons
 * get mapped to a kebab-case key.
 * Alternatively, developers can do:
 * addIcons({ 'airplane': airplane, 'bus': bus, 'car': car, 'train', train });
 */
addIcons({ airplane, bus, car, train });

defineCustomElements();

Angular

src/main.ts

import { bootstrapApplication } from '@angular/platform-browser';
import { RouteReuseStrategy, provideRouter, withPreloading, PreloadAllModules } from '@angular/router';
import { IonicRouteStrategy, provideIonicAngular } from '@ionic/angular';

import { routes } from './app/app.routes';
import { AppComponent } from './app/app.component';

bootstrapApplication(AppComponent, {
  providers: [
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
    provideIonicAngular({
      /**
       * `innerHTMLTemplatesEnabled` must be enabled for rich-content
       * select options to render correctly.
       */
      innerHTMLTemplatesEnabled: true,
    }),
    provideRouter(routes, withPreloading(PreloadAllModules)),
  ],
});

src/app/example.component.html

<ion-list>
  @for (selectInterface of selectInterfaces; track selectInterface) {
  <ion-item>
    <ion-select
      [label]="formatInterfaceLabel(selectInterface)"
      placeholder="Select one"
      [interface]="selectInterface"
      [interfaceOptions]="interfaceOptions"
    >
      <ion-select-option value="airplane" description="Carry-on · Window seat">
        <ion-icon slot="start" size="large" aria-hidden="true" name="airplane"></ion-icon>
        <span class="option-title">Flight</span>
        <span class="option-subtitle">2h 15m · Nonstop</span>
        <ion-badge slot="end" color="tertiary">$279</ion-badge>
      </ion-select-option>
      <ion-select-option value="bus" description="Bike rack · Wi-Fi">
        <ion-icon slot="start" size="large" aria-hidden="true" name="bus"></ion-icon>
        <span class="option-title">Bus</span>
        <span class="option-subtitle">6h 40m · 1 transfer</span>
        <ion-badge slot="end" color="tertiary">$39</ion-badge>
      </ion-select-option>
      <ion-select-option value="car" description="Unlimited miles · GPS">
        <ion-icon slot="start" size="large" aria-hidden="true" name="car"></ion-icon>
        <span class="option-title">Rental Car</span>
        <span class="option-subtitle">5h 10m · Flexible route</span>
        <ion-badge slot="end" color="tertiary">$92</ion-badge>
      </ion-select-option>
      <ion-select-option value="train" description="Reserved seat · Wi-Fi">
        <ion-icon slot="start" size="large" aria-hidden="true" name="train"></ion-icon>
        <span class="option-title">Train</span>
        <span class="option-subtitle">4h 55m · Direct</span>
        <ion-badge slot="end" color="tertiary">$64</ion-badge>
      </ion-select-option>
    </ion-select>
  </ion-item>
  }
</ion-list>

src/app/example.component.ts

import { Component } from '@angular/core';
import { IonBadge, IonIcon, IonItem, IonList, IonSelect, IonSelectOption } from '@ionic/angular';
import { addIcons } from 'ionicons';
import { airplane, bus, car, train } from 'ionicons/icons';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  imports: [IonBadge, IonIcon, IonItem, IonList, IonSelect, IonSelectOption],
})
export class ExampleComponent {
  readonly selectInterfaces = ['alert', 'action-sheet', 'modal', 'popover'];

  /* The interfaceOptions property is for demonstration purposes only. */
  /* It is not required for the rich options to work. */
  readonly interfaceOptions = { header: 'Travel mode' };

  constructor() {
    addIcons({ airplane, bus, car, train });
  }

  formatInterfaceLabel(selectInterface: string): string {
    return selectInterface
      .split('-')
      .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
      .join(' ');
  }
}

src/global.css

/* -----------------------------------------------------*/
/* These styles are for demonstration purposes only.    */
/* They are not required for the rich options to work.  */
/* -----------------------------------------------------*/

/**
* All Interfaces
* ------------------------------------------------
* Override the flex styles so that the title and
* subtitle stack vertically.
*/
.select-option-content div.alert-radio-label-text,
.select-option-content span.action-sheet-button-label-text,
.select-option-content div.select-option-label-text {
  flex-direction: column;
  align-items: start;
  gap: 5px;
}

/* Action Sheet Interface */
ion-action-sheet .select-option-description {
  text-align: start;
}

/* Alert Interface */
ion-alert.select-alert {
  --min-width: 350px;
}

/* Modal, Popover Interfaces */
ion-popover.select-popover ion-list ion-radio.in-item::part(label),
ion-modal.select-modal ion-list ion-radio.in-item::part(label) {
  margin-top: 10px;
  margin-bottom: 10px;
}

/* Custom Select Option Title */
.select-option-content .option-title {
  font-size: 1rem;
  font-weight: 600;
}

/* Custom Select Option Subtitle */
.select-option-content .option-subtitle {
  font-size: 0.8125rem;
  font-weight: 500;
}

React

src/App.tsx

import React from 'react';
import { setupIonicReact, IonApp, IonContent } from '@ionic/react';

/* Core CSS required for Ionic components to work properly */
import '@ionic/react/css/core.css';

/* Basic CSS for apps built with Ionic */
import '@ionic/react/css/normalize.css';
import '@ionic/react/css/structure.css';
import '@ionic/react/css/typography.css';

/* Optional CSS utils that can be commented out */
import '@ionic/react/css/padding.css';
import '@ionic/react/css/float-elements.css';
import '@ionic/react/css/text-alignment.css';
import '@ionic/react/css/text-transformation.css';
import '@ionic/react/css/flex-utils.css';
import '@ionic/react/css/display.css';

/**
 * Ionic Dark Theme
 * -----------------------------------------------------
 * For more information, please see:
 * https://ionicframework.com/docs/theming/dark-mode
 */

// import '@ionic/react/css/palettes/dark.always.css';
// import '@ionic/react/css/palettes/dark.class.css';
import '@ionic/react/css/palettes/dark.system.css';

/* Theme variables */
import './theme/variables.css';

import Example from './main';

/**
 * `innerHTMLTemplatesEnabled` must be enabled for rich-content
 * select options to render correctly.
 */
setupIonicReact({
  innerHTMLTemplatesEnabled: true,
});

export default function App() {
  return (
    <IonApp>
      <IonContent className="ion-padding">
        <Example />
      </IonContent>
    </IonApp>
  );
}

src/main.tsx

import React from 'react';
import { SelectInterface } from '@ionic/core';
import { IonBadge, IonIcon, IonItem, IonList, IonSelect, IonSelectOption } from '@ionic/react';
import { airplane, bus, car, train } from 'ionicons/icons';

import './main.css';

const selectInterfaces: SelectInterface[] = ['alert', 'action-sheet', 'modal', 'popover'];

/* The interfaceOptions property is for demonstration purposes only. */
/* It is not required for the rich options to work. */
const interfaceOptions = { header: 'Travel mode' };

const formatInterfaceLabel = (selectInterface: string) =>
  selectInterface
    .split('-')
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
    .join(' ');

function Example() {
  return (
    <IonList>
      {selectInterfaces.map((selectInterface) => (
        <IonItem key={selectInterface}>
          <IonSelect
            label={formatInterfaceLabel(selectInterface)}
            placeholder="Select one"
            interface={selectInterface}
            interfaceOptions={interfaceOptions}
          >
            <IonSelectOption value="airplane" description="Carry-on · Window seat">
              <IonIcon slot="start" size="large" aria-hidden="true" icon={airplane} />
              <span className="option-title">Flight</span>
              <span className="option-subtitle">2h 15m · Nonstop</span>
              <IonBadge slot="end" color="tertiary">
                $279
              </IonBadge>
            </IonSelectOption>
            <IonSelectOption value="bus" description="Bike rack · Wi-Fi">
              <IonIcon slot="start" size="large" aria-hidden="true" icon={bus} />
              <span className="option-title">Bus</span>
              <span className="option-subtitle">6h 40m · 1 transfer</span>
              <IonBadge slot="end" color="tertiary">
                $39
              </IonBadge>
            </IonSelectOption>
            <IonSelectOption value="car" description="Unlimited miles · GPS">
              <IonIcon slot="start" size="large" aria-hidden="true" icon={car} />
              <span className="option-title">Rental Car</span>
              <span className="option-subtitle">5h 10m · Flexible route</span>
              <IonBadge slot="end" color="tertiary">
                $92
              </IonBadge>
            </IonSelectOption>
            <IonSelectOption value="train" description="Reserved seat · Wi-Fi">
              <IonIcon slot="start" size="large" aria-hidden="true" icon={train} />
              <span className="option-title">Train</span>
              <span className="option-subtitle">4h 55m · Direct</span>
              <IonBadge slot="end" color="tertiary">
                $64
              </IonBadge>
            </IonSelectOption>
          </IonSelect>
        </IonItem>
      ))}
    </IonList>
  );
}
export default Example;

src/main.css

/* -----------------------------------------------------*/
/* These styles are for demonstration purposes only.    */
/* They are not required for the rich options to work.  */
/* -----------------------------------------------------*/

/**
* All Interfaces
* ------------------------------------------------
* Override the flex styles so that the title and
* subtitle stack vertically.
*/
.select-option-content div.alert-radio-label-text,
.select-option-content span.action-sheet-button-label-text,
.select-option-content div.select-option-label-text {
  flex-direction: column;
  align-items: start;
  gap: 5px;
}

/* Action Sheet Interface */
ion-action-sheet .select-option-description {
  text-align: start;
}

/* Alert Interface */
ion-alert.select-alert {
  --min-width: 350px;
}

/* Modal, Popover Interfaces */
ion-popover.select-popover ion-list ion-radio.in-item::part(label),
ion-modal.select-modal ion-list ion-radio.in-item::part(label) {
  margin-top: 10px;
  margin-bottom: 10px;
}

/* Custom Select Option Title */
.select-option-content .option-title {
  font-size: 1rem;
  font-weight: 600;
}

/* Custom Select Option Subtitle */
.select-option-content .option-subtitle {
  font-size: 0.8125rem;
  font-weight: 500;
}

Vue

src/main.ts

import { createApp } from 'vue';
import { IonicVue } from '@ionic/vue';

import App from './App.vue';

/* Core CSS required for Ionic components to work properly */
import '@ionic/vue/css/core.css';

/* Basic CSS for apps built with Ionic */
import '@ionic/vue/css/normalize.css';
import '@ionic/vue/css/structure.css';
import '@ionic/vue/css/typography.css';

/* Optional CSS utils that can be commented out */
import '@ionic/vue/css/padding.css';
import '@ionic/vue/css/float-elements.css';
import '@ionic/vue/css/text-alignment.css';
import '@ionic/vue/css/text-transformation.css';
import '@ionic/vue/css/flex-utils.css';
import '@ionic/vue/css/display.css';

/**
 * Ionic Dark Theme
 * -----------------------------------------------------
 * For more information, please see:
 * https://ionicframework.com/docs/theming/dark-mode
 */

// import '@ionic/vue/css/palettes/dark.always.css';
// import '@ionic/vue/css/palettes/dark.class.css';
import '@ionic/vue/css/palettes/dark.system.css';

/* Theme variables */
import './theme/variables.css';

/**
 * `innerHTMLTemplatesEnabled` must be enabled for rich-content
 * select options to render correctly.
 */
createApp(App)
  .use(IonicVue, {
    innerHTMLTemplatesEnabled: true,
  })
  .mount('#app');

src/components/Example.vue

<template>
  <ion-list>
    <ion-item v-for="selectInterface in selectInterfaces" :key="selectInterface">
      <ion-select
        :label="formatInterfaceLabel(selectInterface)"
        placeholder="Select one"
        :interface="selectInterface"
        :interface-options="interfaceOptions"
      >
        <ion-select-option value="airplane" description="Carry-on · Window seat">
          <ion-icon slot="start" size="large" aria-hidden="true" :icon="airplane"></ion-icon>
          <span class="option-title">Flight</span>
          <span class="option-subtitle">2h 15m · Nonstop</span>
          <ion-badge slot="end" color="tertiary">$279</ion-badge>
        </ion-select-option>
        <ion-select-option value="bus" description="Bike rack · Wi-Fi">
          <ion-icon slot="start" size="large" aria-hidden="true" :icon="bus"></ion-icon>
          <span class="option-title">Bus</span>
          <span class="option-subtitle">6h 40m · 1 transfer</span>
          <ion-badge slot="end" color="tertiary">$39</ion-badge>
        </ion-select-option>
        <ion-select-option value="car" description="Unlimited miles · GPS">
          <ion-icon slot="start" size="large" aria-hidden="true" :icon="car"></ion-icon>
          <span class="option-title">Rental Car</span>
          <span class="option-subtitle">5h 10m · Flexible route</span>
          <ion-badge slot="end" color="tertiary">$92</ion-badge>
        </ion-select-option>
        <ion-select-option value="train" description="Reserved seat · Wi-Fi">
          <ion-icon slot="start" size="large" aria-hidden="true" :icon="train"></ion-icon>
          <span class="option-title">Train</span>
          <span class="option-subtitle">4h 55m · Direct</span>
          <ion-badge slot="end" color="tertiary">$64</ion-badge>
        </ion-select-option>
      </ion-select>
    </ion-item>
  </ion-list>
</template>

<script setup lang="ts">
import { IonBadge, IonIcon, IonItem, IonList, IonSelect, IonSelectOption } from '@ionic/vue';
import { airplane, bus, car, train } from 'ionicons/icons';

const selectInterfaces = ['alert', 'action-sheet', 'modal', 'popover'];

/* The interfaceOptions property is for demonstration purposes only. */
/* It is not required for the rich options to work. */
const interfaceOptions = { header: 'Travel mode' };

const formatInterfaceLabel = (selectInterface: string) =>
  selectInterface
    .split('-')
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
    .join(' ');
</script>

<style>
/* -----------------------------------------------------*/
/* These styles are for demonstration purposes only.    */
/* They are not required for the rich options to work.  */
/* -----------------------------------------------------*/

/**
* All Interfaces
* ------------------------------------------------
* Override the flex styles so that the title and
* subtitle stack vertically.
*/
.select-option-content div.alert-radio-label-text,
.select-option-content span.action-sheet-button-label-text,
.select-option-content div.select-option-label-text {
  flex-direction: column;
  align-items: start;
  gap: 5px;
}

/* Action Sheet Interface */
ion-action-sheet .select-option-description {
  text-align: start;
}

/* Alert Interface */
ion-alert.select-alert {
  --min-width: 350px;
}

/* Modal, Popover Interfaces */
ion-popover.select-popover ion-list ion-radio.in-item::part(label),
ion-modal.select-modal ion-list ion-radio.in-item::part(label) {
  margin-top: 10px;
  margin-bottom: 10px;
}

/* Custom Select Option Title */
.select-option-content .option-title {
  font-size: 1rem;
  font-weight: 600;
}

/* Custom Select Option Subtitle */
.select-option-content .option-subtitle {
  font-size: 0.8125rem;
  font-weight: 500;
}
</style>

Customization

Select 컴포넌트를 구성하는 단위는 두 가지이며 각각 따로 스타일링해야 해요. ion-select 요소는 화면에 선택된 값(들), 또는 값이 없으면 placeholder와 드롭다운 아이콘으로 표시돼요. 위 Interfaces 섹션에서 정의한 인터페이스는 ion-select를 클릭할 때 열리는 다이얼로그예요. 인터페이스에는 ion-select-option 요소를 추가해 정의한 모든 옵션이 들어 있어요. 다음 섹션들에서는 이들을 스타일링할 때의 차이점을 다룰게요.

Styling Select Element

앞서 말했듯이 ion-select 요소는 화면에 표시되는 값(또는 placeholder)과 아이콘으로만 구성돼요. 이를 커스터마이즈하려면 CSS와 CSS custom properties를 조합해 스타일링하면 돼요.

또는 필요한 browser support에 따라 CSS shadow parts를 사용해 select를 스타일링할 수 있어요. ::part을 사용하면 요소의 어떤 CSS 속성이라도 대상으로 지정할 수 있다는 점을 기억해 주세요.

JavaScript

<ion-select aria-label="Fruit" placeholder="Select fruit">
  <ion-select-option value="apples">Apples</ion-select-option>
  <ion-select-option value="oranges">Oranges</ion-select-option>
  <ion-select-option value="bananas">Bananas</ion-select-option>
</ion-select>

<style>
  ion-select {
    --placeholder-color: #971e49;
    --placeholder-opacity: 1;
    width: 100%;
    justify-content: center;
  }

  ion-select::part(placeholder),
  ion-select::part(text) {
    flex: 0 0 auto;
  }

  ion-select::part(placeholder)::first-letter {
    font-size: 24px;
    font-weight: 500;
  }

  ion-select::part(text) {
    color: #545ca7;
  }

  ion-select::part(icon) {
    color: #971e49;
    opacity: 1;
  }
</style>

Angular

src/app/example.component.html

<ion-select aria-label="Fruit" placeholder="Select fruit">
  <ion-select-option value="apples">Apples</ion-select-option>
  <ion-select-option value="oranges">Oranges</ion-select-option>
  <ion-select-option value="bananas">Bananas</ion-select-option>
</ion-select>

src/app/example.component.css

ion-select {
  --placeholder-color: #971e49;
  --placeholder-opacity: 1;
  width: 100%;
  justify-content: center;
}

ion-select::part(placeholder),
ion-select::part(text) {
  flex: 0 0 auto;
}

ion-select::part(placeholder)::first-letter {
  font-size: 24px;
  font-weight: 500;
}

ion-select::part(text) {
  color: #545ca7;
}

ion-select::part(icon) {
  color: #971e49;
  opacity: 1;
}

src/app/example.component.ts

import { Component } from '@angular/core';
import { IonSelect, IonSelectOption } from '@ionic/angular';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonSelect, IonSelectOption],
})
export class ExampleComponent {}

React

src/main.tsx

import React from 'react';
import { IonSelect, IonSelectOption } from '@ionic/react';

import './main.css';

function Example() {
  return (
    <IonSelect aria-label="Fruit" placeholder="Select fruit">
      <IonSelectOption value="apples">Apples</IonSelectOption>
      <IonSelectOption value="oranges">Oranges</IonSelectOption>
      <IonSelectOption value="bananas">Bananas</IonSelectOption>
    </IonSelect>
  );
}
export default Example;

src/main.css

ion-select {
  --placeholder-color: #971e49;
  --placeholder-opacity: 1;
  width: 100%;
  justify-content: center;
}

ion-select::part(placeholder),
ion-select::part(text) {
  flex: 0 0 auto;
}

ion-select::part(placeholder)::first-letter {
  font-size: 24px;
  font-weight: 500;
}

ion-select::part(text) {
  color: #545ca7;
}

ion-select::part(icon) {
  color: #971e49;
  opacity: 1;
}

Vue

<template>
  <ion-select aria-label="Fruit" placeholder="Select fruit">
    <ion-select-option value="apples">Apples</ion-select-option>
    <ion-select-option value="oranges">Oranges</ion-select-option>
    <ion-select-option value="bananas">Bananas</ion-select-option>
  </ion-select>
</template>

<script setup lang="ts">
  import { IonSelect, IonSelectOption } from '@ionic/vue';
</script>

<style>
  ion-select {
    --placeholder-color: #971e49;
    --placeholder-opacity: 1;
    width: 100%;
    justify-content: center;
  }

  ion-select::part(placeholder),
  ion-select::part(text) {
    flex: 0 0 auto;
  }

  ion-select::part(placeholder)::first-letter {
    font-size: 24px;
    font-weight: 500;
  }

  ion-select::part(text) {
    color: #545ca7;
  }

  ion-select::part(icon) {
    color: #971e49;
    opacity: 1;
  }
</style>

Styling Select Interface

인터페이스 다이얼로그를 커스터마이즈하려면 해당 인터페이스 문서의 스타일링 섹션(CSS shadow parts, CSS custom properties, slots)을 따라야 해요:

하지만 Select Option은 스타일링을 쉽게 하기 위해 클래스를 설정하고 오버레이 옵션에 클래스를 전달하는 기능을 제공해요. 옵션 커스터마이징의 예시는 Select Options documentation을 참고해 주세요.

Custom Toggle Icons

select 텍스트 옆에 표시되는 아이콘은 toggleIcon 및/또는 expandedIcon 속성을 사용해 어떤 Ionicon으로든 설정할 수 있어요.

JavaScript

<ion-list>
  <ion-item>
    <ion-select
      interface="popover"
      toggle-icon="add"
      expanded-icon="remove"
      aria-label="fruit"
      placeholder="Select fruit"
    >
      <ion-select-option value="apples">Apples</ion-select-option>
      <ion-select-option value="oranges">Oranges</ion-select-option>
      <ion-select-option value="bananas">Bananas</ion-select-option>
    </ion-select>
  </ion-item>
</ion-list>

Angular

src/app/example.component.html

<ion-list>
  <ion-item>
    <ion-select
      interface="popover"
      toggleIcon="add"
      expandedIcon="remove"
      aria-label="fruit"
      placeholder="Select fruit"
    >
      <ion-select-option value="apples">Apples</ion-select-option>
      <ion-select-option value="oranges">Oranges</ion-select-option>
      <ion-select-option value="bananas">Bananas</ion-select-option>
    </ion-select>
  </ion-item>
</ion-list>

src/app/example.component.ts

import { Component } from '@angular/core';
import { IonItem, IonList, IonSelect, IonSelectOption } from '@ionic/angular';

import { addIcons } from 'ionicons';
import { add, remove } from 'ionicons/icons';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonItem, IonList, IonSelect, IonSelectOption],
})
export class ExampleComponent {
  constructor() {
    /**
     * Any icons you want to use in your application
     * can be registered in app.component.ts and then
     * referenced by name anywhere in your application.
     */
    addIcons({ add, remove });
  }
}

React

import React from 'react';
import { IonItem, IonList, IonSelect, IonSelectOption } from '@ionic/react';
import { add, remove } from 'ionicons/icons';

function Example() {
  return (
    <IonList>
      <IonItem>
        <IonSelect
          interface="popover"
          toggleIcon={add}
          expandedIcon={remove}
          aria-label="fruit"
          placeholder="Select fruit"
        >
          <IonSelectOption value="apples">Apples</IonSelectOption>
          <IonSelectOption value="oranges">Oranges</IonSelectOption>
          <IonSelectOption value="bananas">Bananas</IonSelectOption>
        </IonSelect>
      </IonItem>
    </IonList>
  );
}
export default Example;

Vue

<template>
  <ion-list>
    <ion-item>
      <ion-select
        interface="popover"
        :toggle-icon="add"
        :expanded-icon="remove"
        aria-label="fruit"
        placeholder="Select fruit"
      >
        <ion-select-option value="apples">Apples</ion-select-option>
        <ion-select-option value="oranges">Oranges</ion-select-option>
        <ion-select-option value="bananas">Bananas</ion-select-option>
      </ion-select>
    </ion-item>
  </ion-list>
</template>

<script setup lang="ts">
  import { IonItem, IonList, IonSelect, IonSelectOption } from '@ionic/vue';
  import { add, remove } from 'ionicons/icons';
</script>

Icon Flip Behavior

기본적으로 select가 열려 있으면 토글 아이콘은 md 모드에서 자동으로 회전하고 ios 모드에서는 고정 상태를 유지해요. 이 동작은 CSS로 커스터마이즈할 수 있어요.

아래 예시는 기본 아이콘이 수직 대칭이라 ios에서의 플립 동작을 더 잘 보여주기 위해 custom toggleIcon도 사용해요.

JavaScript

<ion-list>
  <ion-item>
    <ion-select
      class="always-flip"
      toggle-icon="caret-down-sharp"
      interface="popover"
      label="Icon flips on both modes"
      placeholder="Select fruit"
    >
      <ion-select-option value="apples">Apples</ion-select-option>
      <ion-select-option value="oranges">Oranges</ion-select-option>
      <ion-select-option value="bananas">Bananas</ion-select-option>
    </ion-select>
  </ion-item>
  <ion-item>
    <ion-select
      class="never-flip"
      toggle-icon="caret-down-sharp"
      interface="popover"
      label="Icon never flips"
      placeholder="Select fruit"
    >
      <ion-select-option value="apples">Apples</ion-select-option>
      <ion-select-option value="oranges">Oranges</ion-select-option>
      <ion-select-option value="bananas">Bananas</ion-select-option>
    </ion-select>
  </ion-item>
</ion-list>

<style>
  ion-select.always-flip::part(icon) {
    transition: transform 0.15s cubic-bezier(0.4, 0, 0.2, 1);
  }

  ion-select.always-flip.select-expanded::part(icon) {
    transform: rotate(180deg);
  }

  ion-select.never-flip::part(icon) {
    transform: none;
  }
</style>

Angular

src/app/example.component.html

<ion-list>
  <ion-item>
    <ion-select
      class="always-flip"
      toggleIcon="caret-down-sharp"
      interface="popover"
      label="Icon flips on both modes"
      placeholder="Select fruit"
    >
      <ion-select-option value="apples">Apples</ion-select-option>
      <ion-select-option value="oranges">Oranges</ion-select-option>
      <ion-select-option value="bananas">Bananas</ion-select-option>
    </ion-select>
  </ion-item>
  <ion-item>
    <ion-select
      class="never-flip"
      toggleIcon="caret-down-sharp"
      interface="popover"
      label="Icon never flips"
      placeholder="Select fruit"
    >
      <ion-select-option value="apples">Apples</ion-select-option>
      <ion-select-option value="oranges">Oranges</ion-select-option>
      <ion-select-option value="bananas">Bananas</ion-select-option>
    </ion-select>
  </ion-item>
</ion-list>

src/app/example.component.css

ion-select.always-flip::part(icon) {
  transition: transform 0.15s cubic-bezier(0.4, 0, 0.2, 1);
}

ion-select.always-flip.select-expanded::part(icon) {
  transform: rotate(180deg);
}

ion-select.never-flip::part(icon) {
  transform: none;
}

src/app/example.component.ts

import { Component } from '@angular/core';
import { IonItem, IonList, IonSelect, IonSelectOption } from '@ionic/angular';

import { addIcons } from 'ionicons';
import { caretDownSharp } from 'ionicons/icons';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonItem, IonList, IonSelect, IonSelectOption],
})
export class ExampleComponent {
  constructor() {
    /**
     * Any icons you want to use in your application
     * can be registered in app.component.ts and then
     * referenced by name anywhere in your application.
     */
    addIcons({ caretDownSharp });
  }
}

React

src/main.tsx

import React from 'react';
import { IonItem, IonList, IonSelect, IonSelectOption } from '@ionic/react';
import { caretDownSharp } from 'ionicons/icons';

import './main.css';

function Example() {
  return (
    <IonList>
      <IonItem>
        <IonSelect
          className="always-flip"
          toggleIcon={caretDownSharp}
          interface="popover"
          label="Icon flips on both modes"
          placeholder="Select fruit"
        >
          <IonSelectOption value="apples">Apples</IonSelectOption>
          <IonSelectOption value="oranges">Oranges</IonSelectOption>
          <IonSelectOption value="bananas">Bananas</IonSelectOption>
        </IonSelect>
      </IonItem>
      <IonItem>
        <IonSelect
          className="never-flip"
          toggleIcon={caretDownSharp}
          interface="popover"
          label="Icon never flips"
          placeholder="Select fruit"
        >
          <IonSelectOption value="apples">Apples</IonSelectOption>
          <IonSelectOption value="oranges">Oranges</IonSelectOption>
          <IonSelectOption value="bananas">Bananas</IonSelectOption>
        </IonSelect>
      </IonItem>
    </IonList>
  );
}
export default Example;

src/main.css

ion-select.always-flip::part(icon) {
  transition: transform 0.15s cubic-bezier(0.4, 0, 0.2, 1);
}

ion-select.always-flip.select-expanded::part(icon) {
  transform: rotate(180deg);
}

ion-select.never-flip::part(icon) {
  transform: none;
}

Vue

<template>
  <ion-list>
    <ion-item>
      <ion-select
        class="always-flip"
        :toggle-icon="caretDownSharp"
        interface="popover"
        label="Icon flips on both modes"
        placeholder="Select fruit"
      >
        <ion-select-option value="apples">Apples</ion-select-option>
        <ion-select-option value="oranges">Oranges</ion-select-option>
        <ion-select-option value="bananas">Bananas</ion-select-option>
      </ion-select>
    </ion-item>
    <ion-item>
      <ion-select
        class="never-flip"
        :toggle-icon="caretDownSharp"
        interface="popover"
        label="Icon never flips"
        placeholder="Select fruit"
      >
        <ion-select-option value="apples">Apples</ion-select-option>
        <ion-select-option value="oranges">Oranges</ion-select-option>
        <ion-select-option value="bananas">Bananas</ion-select-option>
      </ion-select>
    </ion-item>
  </ion-list>
</template>

<script setup lang="ts">
  import { IonItem, IonList, IonSelect, IonSelectOption } from '@ionic/vue';
  import { caretDownSharp } from 'ionicons/icons';
</script>

<style>
  ion-select.always-flip::part(icon) {
    transition: transform 0.15s cubic-bezier(0.4, 0, 0.2, 1);
  }

  ion-select.always-flip.select-expanded::part(icon) {
    transform: rotate(180deg);
  }

  ion-select.never-flip::part(icon) {
    transform: none;
  }
</style>

Typeahead Component

타입어헤드(typeahead) 또는 자동완성 기능은 기존 Ionic 컴포넌트로 만들 수 있어요. 사용 가능한 화면 공간을 최대한 활용하려면 ion-modal을 사용하는 것을 권장해요.

JavaScript

<ion-content color="light">
  <div class="container">
    <ion-list inset="true">
      <ion-item button="true" detail="false" id="select-fruits">
        <ion-label>Favorite Fruits</ion-label>
        <div slot="end" id="selected-fruits">0 Items</div>
      </ion-item>
    </ion-list>
  </div>
</ion-content>

<ion-modal trigger="select-fruits">
  <ion-header>
    <ion-toolbar>
      <ion-buttons slot="start">
        <ion-button onclick="cancelChanges()">Cancel</ion-button>
      </ion-buttons>
      <ion-title>Favorite Fruits</ion-title>
      <ion-buttons slot="end">
        <ion-button onclick="confirmChanges()">Done</ion-button>
      </ion-buttons>
    </ion-toolbar>
    <ion-toolbar>
      <ion-searchbar></ion-searchbar>
    </ion-toolbar>
  </ion-header>
  <ion-content color="light" class="ion-padding">
    <ion-list id="modal-list" inset="true"> </ion-list>
  </ion-content>
</ion-modal>

<script>
  const list = document.querySelector('ion-list#modal-list');
  const modal = document.querySelector('ion-modal');
  const searchbar = document.querySelector('ion-searchbar');
  const selectedFruitsText = document.querySelector('#selected-fruits');
  const fruits = [
    { text: 'Apple', value: 'apple' },
    { text: 'Apricot', value: 'apricot' },
    { text: 'Banana', value: 'banana' },
    { text: 'Blackberry', value: 'blackberry' },
    { text: 'Blueberry', value: 'blueberry' },
    { text: 'Cherry', value: 'cherry' },
    { text: 'Cranberry', value: 'cranberry' },
    { text: 'Grape', value: 'grape' },
    { text: 'Grapefruit', value: 'grapefruit' },
    { text: 'Guava', value: 'guava' },
    { text: 'Jackfruit', value: 'jackfruit' },
    { text: 'Lime', value: 'lime' },
    { text: 'Mango', value: 'mango' },
    { text: 'Nectarine', value: 'nectarine' },
    { text: 'Orange', value: 'orange' },
    { text: 'Papaya', value: 'papaya' },
    { text: 'Passionfruit', value: 'passionfruit' },
    { text: 'Peach', value: 'peach' },
    { text: 'Pear', value: 'pear' },
    { text: 'Plantain', value: 'plantain' },
    { text: 'Plum', value: 'plum' },
    { text: 'Pineapple', value: 'pineapple' },
    { text: 'Pomegranate', value: 'pomegranate' },
    { text: 'Raspberry', value: 'raspberry' },
    { text: 'Strawberry', value: 'strawberry' },
  ];

  /**
   * This is the confirmed
   * list of selected fruits. It
   * is only updated once the "Done"
   * button is pressed in the modal.
   */
  var selectedFruits = [];

  /**
   * This is the working list of
   * selected fruits. It tracks any
   * uncommitted changes that the user
   * makes in the modal. If the user pressed
   * the "Cancel" button then this is
   * reset to the value of the confirmed
   * selected fruits.
   */
  var workingSelectedFruits = [];

  /**
   * Filter the list of fruits base
   * on the search query. If no query
   * is provided then the entire list
   * will be returned.
   */
  function filterList(searchQuery = undefined) {
    if (searchQuery === undefined) return fruits;

    const normalizedQuery = searchQuery.toLowerCase();

    return fruits.filter((fruit) => fruit.text.toLowerCase().includes(normalizedQuery));
  }

  /**
   * Render a filtered list of fruits
   * inside of the modal based on the
   * search query.
   */
  function renderList(searchQuery = undefined) {
    const data = filterList(searchQuery);
    let template = '';

    data.forEach((item, index) => {
      const checked = workingSelectedFruits.includes(item.value);
      template += `
        <ion-item>
          <ion-checkbox value="${item.value}" checked="${checked}">${item.text}</ion-checkbox>
        </ion-item>
      `;
    });

    list.innerHTML = template;
  }

  /**
   * Formats the selected fruits in
   * an easier to read way. If only
   * 1 fruit is selected, then the
   * fruit name will be rendered.
   * Otherwise the number of fruits
   * selected will be rendered.
   */
  function formatData(data) {
    if (data.length === 1) {
      const fruit = fruits.find((fruit) => fruit.value === data[0]);
      return fruit.text;
    }

    return `${data.length} items`;
  }

  /**
   * Reset any working changes
   * and dismiss the modal.
   */
  function cancelChanges() {
    workingSelectedFruits = [...selectedFruits];
    modal.dismiss(undefined, 'cancel');
  }

  /**
   * Return the selected
   * fruits to the parent page.
   */
  function confirmChanges() {
    selectedFruits = [...workingSelectedFruits];
    modal.dismiss(selectedFruits);
  }

  // Listen for all ionChange events from the checkbox
  modal.addEventListener('ionChange', (event) => {
    if (event.target.tagName !== 'ION-CHECKBOX') {
      return;
    }

    const { checked, value } = event.detail;

    if (checked) {
      workingSelectedFruits = [...workingSelectedFruits, value];
    } else {
      workingSelectedFruits = workingSelectedFruits.filter((fruit) => fruit !== value);
    }
  });

  /**
   * As users type into the searchbar
   * we need to update the view with
   * the filtered list.
   */
  searchbar.addEventListener('ionInput', (event) => {
    renderList(event.target.value);
  });

  /**
   * When the modal is about to dismiss
   * update the parent page with the
   * selected fruits.
   */
  modal.addEventListener('ionModalWillDismiss', (event) => {
    const { data } = event.detail;

    if (data === undefined) return;

    const selectedText = formatData(data);

    selectedFruitsText.innerText = selectedText;
  });

  /**
   * When the modal has completed we need to
   * reset the filtered state of the list.
   */
  modal.addEventListener('ionModalDidDismiss', (event) => {
    searchbar.value = undefined;
    renderList();
  });

  renderList();
</script>

Angular

src/app/example.component.html

<ion-content color="light">
  <ion-list [inset]="true">
    <ion-item [button]="true" [detail]="false" id="select-fruits">
      <ion-label>Favorite Fruits</ion-label>
      <div slot="end" id="selected-fruits">{{ selectedFruitsText }}</div>
    </ion-item>
  </ion-list>
</ion-content>

<ion-modal trigger="select-fruits" #modal>
  <ng-template>
    <app-typeahead
      class="ion-page"
      title="Favorite Fruits"
      [items]="fruits"
      [selectedItems]="selectedFruits"
      (selectionChange)="fruitSelectionChanged($event)"
      (selectionCancel)="modal.dismiss()"
    ></app-typeahead>
  </ng-template>
</ion-modal>

src/app/example.component.ts

import { Component, ViewChild } from '@angular/core';
import { IonContent, IonItem, IonLabel, IonList, IonModal } from '@ionic/angular';
import { Item } from './types';

import { TypeaheadComponent } from './typeahead.component';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonContent, IonItem, IonLabel, IonList, IonModal, TypeaheadComponent],
})
export class ExampleComponent {
  @ViewChild('modal', { static: true }) modal!: IonModal;

  selectedFruitsText = '0 Items';
  selectedFruits: string[] = [];

  fruits: Item[] = [
    { text: 'Apple', value: 'apple' },
    { text: 'Apricot', value: 'apricot' },
    { text: 'Banana', value: 'banana' },
    { text: 'Blackberry', value: 'blackberry' },
    { text: 'Blueberry', value: 'blueberry' },
    { text: 'Cherry', value: 'cherry' },
    { text: 'Cranberry', value: 'cranberry' },
    { text: 'Grape', value: 'grape' },
    { text: 'Grapefruit', value: 'grapefruit' },
    { text: 'Guava', value: 'guava' },
    { text: 'Jackfruit', value: 'jackfruit' },
    { text: 'Lime', value: 'lime' },
    { text: 'Mango', value: 'mango' },
    { text: 'Nectarine', value: 'nectarine' },
    { text: 'Orange', value: 'orange' },
    { text: 'Papaya', value: 'papaya' },
    { text: 'Passionfruit', value: 'passionfruit' },
    { text: 'Peach', value: 'peach' },
    { text: 'Pear', value: 'pear' },
    { text: 'Plantain', value: 'plantain' },
    { text: 'Plum', value: 'plum' },
    { text: 'Pineapple', value: 'pineapple' },
    { text: 'Pomegranate', value: 'pomegranate' },
    { text: 'Raspberry', value: 'raspberry' },
    { text: 'Strawberry', value: 'strawberry' },
  ];

  /**
   * Formats the display text based on the selected fruits.
   * @param data - Array of selected fruit values
   * @returns A formatted string for display
   */
  private formatData(data: string[]): string {
    if (data.length === 1) {
      const fruit = this.fruits.find((fruit) => fruit.value === data[0]);
      return fruit ? fruit.text : '';
    }
    return `${data.length} items`;
  }

  /**
   * Handles fruit selection changes and updates the selected fruits and text.
   * @param fruits - Array of selected fruit values
   */
  fruitSelectionChanged(fruits: string[]) {
    this.selectedFruits = fruits;
    this.selectedFruitsText = this.formatData(this.selectedFruits);
    this.modal.dismiss();
  }
}

src/app/typeahead.component.html

<ion-header>
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-button (click)="cancelChanges()">Cancel</ion-button>
    </ion-buttons>
    <ion-title>{{ title }}</ion-title>
    <ion-buttons slot="end">
      <ion-button (click)="confirmChanges()">Done</ion-button>
    </ion-buttons>
  </ion-toolbar>
  <ion-toolbar>
    <ion-searchbar (ionInput)="searchbarInput($event)"></ion-searchbar>
  </ion-toolbar>
</ion-header>

<ion-content color="light" class="ion-padding">
  <ion-list id="modal-list" [inset]="true">
    @for (item of filteredItems; track item.value) {
    <ion-item>
      <ion-checkbox [value]="item.value" [checked]="isChecked(item.value)" (ionChange)="checkboxChange($event)"
        >{{ item.text }}</ion-checkbox
      >
    </ion-item>
    }
  </ion-list>
</ion-content>

src/app/typeahead.component.ts

import { Component, Input, Output, EventEmitter } from '@angular/core';
import type { OnInit } from '@angular/core';

import {
  IonButton,
  IonButtons,
  IonCheckbox,
  IonContent,
  IonHeader,
  IonItem,
  IonList,
  IonSearchbar,
  IonTitle,
  IonToolbar,
} from '@ionic/angular';

import { Item } from './types';

@Component({
  selector: 'app-typeahead',
  templateUrl: 'typeahead.component.html',
  imports: [
    IonButton,
    IonButtons,
    IonCheckbox,
    IonContent,
    IonHeader,
    IonItem,
    IonList,
    IonSearchbar,
    IonTitle,
    IonToolbar,
  ],
})
export class TypeaheadComponent implements OnInit {
  @Input() items: Item[] = [];
  @Input() selectedItems: string[] = [];
  @Input() title = 'Select Items';

  @Output() selectionCancel = new EventEmitter<void>();
  @Output() selectionChange = new EventEmitter<string[]>();

  filteredItems: Item[] = [];
  workingSelectedValues: string[] = [];

  ngOnInit() {
    this.filteredItems = [...this.items];
    this.workingSelectedValues = [...this.selectedItems];
  }

  cancelChanges() {
    this.selectionCancel.emit();
  }

  confirmChanges() {
    this.selectionChange.emit(this.workingSelectedValues);
  }

  searchbarInput(event: Event) {
    const inputElement = event.target as HTMLInputElement;
    this.filterList(inputElement.value);
  }

  /**
   * Update the rendered view with
   * the provided search query. If no
   * query is provided, all data
   * will be rendered.
   */
  filterList(searchQuery: string | undefined) {
    /**
     * If no search query is defined,
     * return all options.
     */
    if (searchQuery === undefined || searchQuery.trim() === '') {
      this.filteredItems = [...this.items];
    } else {
      /**
       * Otherwise, normalize the search
       * query and check to see which items
       * contain the search query as a substring.
       */
      const normalizedQuery = searchQuery.toLowerCase();
      this.filteredItems = this.items.filter((item) => item.text.toLowerCase().includes(normalizedQuery));
    }
  }

  isChecked(value: string): boolean {
    return this.workingSelectedValues.includes(value);
  }

  checkboxChange(event: CustomEvent<{ checked: boolean; value: string }>) {
    const { checked, value } = event.detail;

    if (checked) {
      this.workingSelectedValues = [...this.workingSelectedValues, value];
    } else {
      this.workingSelectedValues = this.workingSelectedValues.filter((item) => item !== value);
    }
  }
}

src/app/types.ts

export interface Item {
  text: string;
  value: string;
}

React

src/main.tsx

import React, { useRef, useState } from 'react';
import { IonContent, IonItem, IonLabel, IonList, IonModal } from '@ionic/react';
import AppTypeahead from './AppTypeahead';

import type { Item } from './types';

const fruits: Item[] = [
  { text: 'Apple', value: 'apple' },
  { text: 'Apricot', value: 'apricot' },
  { text: 'Banana', value: 'banana' },
  { text: 'Blackberry', value: 'blackberry' },
  { text: 'Blueberry', value: 'blueberry' },
  { text: 'Cherry', value: 'cherry' },
  { text: 'Cranberry', value: 'cranberry' },
  { text: 'Grape', value: 'grape' },
  { text: 'Grapefruit', value: 'grapefruit' },
  { text: 'Guava', value: 'guava' },
  { text: 'Jackfruit', value: 'jackfruit' },
  { text: 'Lime', value: 'lime' },
  { text: 'Mango', value: 'mango' },
  { text: 'Nectarine', value: 'nectarine' },
  { text: 'Orange', value: 'orange' },
  { text: 'Papaya', value: 'papaya' },
  { text: 'Passionfruit', value: 'passionfruit' },
  { text: 'Peach', value: 'peach' },
  { text: 'Pear', value: 'pear' },
  { text: 'Plantain', value: 'plantain' },
  { text: 'Plum', value: 'plum' },
  { text: 'Pineapple', value: 'pineapple' },
  { text: 'Pomegranate', value: 'pomegranate' },
  { text: 'Raspberry', value: 'raspberry' },
  { text: 'Strawberry', value: 'strawberry' },
];

function Example() {
  const [selectedFruitsText, setSelectedFruitsText] = useState<string>('0 Items');
  const [selectedFruits, setSelectedFruits] = useState<string[]>([]);

  const modal = useRef<HTMLIonModalElement>(null);

  const formatData = (data: string[]) => {
    if (data.length === 1) {
      const fruit = fruits.find((fruit) => fruit.value === data[0])!;
      return fruit.text;
    }

    return `${data.length} items`;
  };

  const fruitSelectionChanged = (fruits: string[]) => {
    setSelectedFruits(fruits);
    setSelectedFruitsText(formatData(fruits));
    modal.current?.dismiss();
  };

  return (
    <>
      <IonContent color="light">
        <IonList inset={true}>
          <IonItem button={true} detail={false} id="select-fruits">
            <IonLabel>Favorite Fruits</IonLabel>
            <div slot="end" id="selected-fruits">
              {selectedFruitsText}
            </div>
          </IonItem>
        </IonList>
      </IonContent>

      <IonModal trigger="select-fruits" ref={modal}>
        <AppTypeahead
          title="Favorite Fruits"
          items={fruits}
          selectedItems={selectedFruits}
          onSelectionCancel={() => modal.current?.dismiss()}
          onSelectionChange={fruitSelectionChanged}
        />
      </IonModal>
    </>
  );
}
export default Example;

src/types.ts

export interface Item {
  text: string;
  value: string;
}

src/AppTypeahead.tsx

import React, { useState } from 'react';
import {
  IonButton,
  IonButtons,
  IonCheckbox,
  IonContent,
  IonHeader,
  IonItem,
  IonList,
  IonTitle,
  IonSearchbar,
  IonToolbar,
} from '@ionic/react';
import type { CheckboxCustomEvent } from '@ionic/react';
import type { Item } from './types';

interface TypeaheadProps {
  items: Item[];
  selectedItems: string[];
  title?: string;
  onSelectionCancel?: () => void;
  onSelectionChange?: (items: string[]) => void;
}

function AppTypeahead(props: TypeaheadProps) {
  const [filteredItems, setFilteredItems] = useState<Item[]>([...props.items]);
  const [workingSelectedValues, setWorkingSelectedValues] = useState<string[]>([...props.selectedItems]);

  const isChecked = (value: string) => {
    return workingSelectedValues.find((item) => item === value) !== undefined;
  };

  const cancelChanges = () => {
    const { onSelectionCancel } = props;
    if (onSelectionCancel !== undefined) {
      onSelectionCancel();
    }
  };

  const confirmChanges = () => {
    const { onSelectionChange } = props;
    if (onSelectionChange !== undefined) {
      onSelectionChange(workingSelectedValues);
    }
  };

  const searchbarInput = (event: any) => {
    filterList(event.target.value);
  };

  /**
   * Update the rendered view with
   * the provided search query. If no
   * query is provided, all data
   * will be rendered.
   */
  const filterList = (searchQuery: string | null | undefined) => {
    /**
     * If no search query is defined,
     * return all options.
     */
    if (searchQuery === undefined || searchQuery === null) {
      setFilteredItems([...props.items]);
    } else {
      /**
       * Otherwise, normalize the search
       * query and check to see which items
       * contain the search query as a substring.
       */
      const normalizedQuery = searchQuery.toLowerCase();
      setFilteredItems(
        props.items.filter((item) => {
          return item.text.toLowerCase().includes(normalizedQuery);
        })
      );
    }
  };

  const checkboxChange = (event: CheckboxCustomEvent) => {
    const { checked, value } = event.detail;

    if (checked) {
      setWorkingSelectedValues([...workingSelectedValues, value]);
    } else {
      setWorkingSelectedValues(workingSelectedValues.filter((item) => item !== value));
    }
  };

  return (
    <>
      <IonHeader>
        <IonToolbar>
          <IonButtons slot="start">
            <IonButton onClick={cancelChanges}>Cancel</IonButton>
          </IonButtons>
          <IonTitle>{props.title}</IonTitle>
          <IonButtons slot="end">
            <IonButton onClick={confirmChanges}>Done</IonButton>
          </IonButtons>
        </IonToolbar>
        <IonToolbar>
          <IonSearchbar onIonInput={searchbarInput}></IonSearchbar>
        </IonToolbar>
      </IonHeader>

      <IonContent color="light" class="ion-padding">
        <IonList id="modal-list" inset={true}>
          {filteredItems.map((item) => (
            <IonItem key={item.value}>
              <IonCheckbox value={item.value} checked={isChecked(item.value)} onIonChange={checkboxChange}>
                {item.text}
              </IonCheckbox>
            </IonItem>
          ))}
        </IonList>
      </IonContent>
    </>
  );
}
export default AppTypeahead;

Vue

src/components/Example.vue

<template>
  <ion-content color="light">
    <ion-list :inset="true">
      <ion-item :button="true" :detail="false" id="select-fruits">
        <ion-label>Favorite Fruits</ion-label>
        <div slot="end" id="selected-fruits">{{ selectedFruitsText }}</div>
      </ion-item>
    </ion-list>
  </ion-content>

  <ion-modal trigger="select-fruits" ref="modal">
    <app-typeahead
      class="ion-page"
      title="Favorite Fruits"
      :items="fruits"
      :selectedItems="selectedFruits"
      @selection-change="fruitSelectionChanged($event)"
      @selection-cancel="modal.$el.dismiss()"
    ></app-typeahead>
  </ion-modal>
</template>

<script setup lang="ts">
  import { IonContent, IonItem, IonLabel, IonList, IonModal } from '@ionic/vue';
  import { ref } from 'vue';
  import type { Item } from '../types';
  import AppTypeahead from './AppTypeahead.vue';

  const fruits: Item[] = [
    { text: 'Apple', value: 'apple' },
    { text: 'Apricot', value: 'apricot' },
    { text: 'Banana', value: 'banana' },
    { text: 'Blackberry', value: 'blackberry' },
    { text: 'Blueberry', value: 'blueberry' },
    { text: 'Cherry', value: 'cherry' },
    { text: 'Cranberry', value: 'cranberry' },
    { text: 'Grape', value: 'grape' },
    { text: 'Grapefruit', value: 'grapefruit' },
    { text: 'Guava', value: 'guava' },
    { text: 'Jackfruit', value: 'jackfruit' },
    { text: 'Lime', value: 'lime' },
    { text: 'Mango', value: 'mango' },
    { text: 'Nectarine', value: 'nectarine' },
    { text: 'Orange', value: 'orange' },
    { text: 'Papaya', value: 'papaya' },
    { text: 'Passionfruit', value: 'passionfruit' },
    { text: 'Peach', value: 'peach' },
    { text: 'Pear', value: 'pear' },
    { text: 'Plantain', value: 'plantain' },
    { text: 'Plum', value: 'plum' },
    { text: 'Pineapple', value: 'pineapple' },
    { text: 'Pomegranate', value: 'pomegranate' },
    { text: 'Raspberry', value: 'raspberry' },
    { text: 'Strawberry', value: 'strawberry' },
  ];
  const modal = ref();
  const selectedFruitsText = ref('0 Items');
  const selectedFruits = ref([]);

  const formatData = (data: string[]) => {
    if (data.length === 1) {
      const fruit = fruits.find((fruit) => fruit.value === data[0]);
      return fruit.text;
    }

    return `${data.length} items`;
  };

  const fruitSelectionChanged = (fruits: string[]) => {
    selectedFruits.value = fruits;
    selectedFruitsText.value = formatData(selectedFruits.value);
    modal.value.$el.dismiss();
  };
</script>

src/types.ts

export interface Item {
  text: string;
  value: string;
}

src/components/AppTypeahead.vue

<template>
  <ion-header>
    <ion-toolbar>
      <ion-buttons slot="start">
        <ion-button @click="cancelChanges()">Cancel</ion-button>
      </ion-buttons>
      <ion-title>{{ $props.title }}</ion-title>
      <ion-buttons slot="end">
        <ion-button @click="confirmChanges()">Done</ion-button>
      </ion-buttons>
    </ion-toolbar>
    <ion-toolbar>
      <ion-searchbar @ionInput="searchbarInput($event)"></ion-searchbar>
    </ion-toolbar>
  </ion-header>

  <ion-content color="light" class="ion-padding">
    <ion-list id="modal-list" :inset="true">
      <ion-item v-for="item in filteredItems" :key="item.value">
        <ion-checkbox :value="item.value" :checked="isChecked(item.value)" @ionChange="checkboxChange($event)"
          >{{ item.text }}</ion-checkbox
        >
      </ion-item>
    </ion-list>
  </ion-content>
</template>

<script setup lang="ts">
  import {
    IonButton,
    IonButtons,
    IonCheckbox,
    IonContent,
    IonHeader,
    IonItem,
    IonList,
    IonTitle,
    IonSearchbar,
    IonToolbar,
  } from '@ionic/vue';
  import type { CheckboxCustomEvent, SearchbarCustomEvent } from '@ionic/vue';
  import { ref } from 'vue';

  interface Props {
    items: Array<any>;
    selectedItems: Array<any>;
    title?: string;
  }

  const props = withDefaults(defineProps<Props>(), {
    title: 'Select Items',
  });

  const emit = defineEmits<{
    'selection-cancel': [];
    'selection-change': [value: any[]];
  }>();

  const filteredItems = ref([...props.items]);
  const workingSelectedValues = ref([...props.selectedItems]);

  const isChecked = (value: string) => {
    return workingSelectedValues.value.find((item) => item === value) !== undefined;
  };

  const cancelChanges = () => {
    emit('selection-cancel');
  };

  const confirmChanges = () => {
    emit('selection-change', workingSelectedValues.value);
  };

  const searchbarInput = (event: SearchbarCustomEvent) => {
    filterList(event.target.value);
  };

  /**
   * Update the rendered view with
   * the provided search query. If no
   * query is provided, all data
   * will be rendered.
   */
  const filterList = (searchQuery: string | undefined) => {
    /**
     * If no search query is defined,
     * return all options.
     */
    if (searchQuery === undefined) {
      filteredItems.value = [...props.items];
    } else {
      /**
       * Otherwise, normalize the search
       * query and check to see which items
       * contain the search query as a substring.
       */
      const normalizedQuery = searchQuery.toLowerCase();
      filteredItems.value = props.items.filter((item) => {
        return item.text.toLowerCase().includes(normalizedQuery);
      });
    }
  };

  const checkboxChange = (event: CheckboxCustomEvent) => {
    const { checked, value } = event.detail;

    if (checked) {
      workingSelectedValues.value = [...workingSelectedValues.value, value];
    } else {
      workingSelectedValues.value = workingSelectedValues.value.filter((item) => item !== value);
    }
  };
</script>

Helper & Error Text

헬퍼 텍스트와 에러 텍스트는 helperText와 errorText 속성으로 select 안에서 사용할 수 있어요. 에러 텍스트는 ion-invalid와 ion-touched 클래스가 ion-select에 추가되지 않으면 표시되지 않아요. 이렇게 하면 사용자가 데이터를 입력할 기회를 갖기 전에 에러가 표시되지 않아요.

Angular에서는 폼 검증을 통해 자동으로 처리돼요. JavaScript, React, Vue에서는 사용자 자신의 검증에 따라 클래스를 수동으로 추가해야 해요.

JavaScript

<form id="my-form">
  <ion-select
    label="Favorite fruit"
    placeholder="Select fruit"
    helper-text="Select your favorite fruit"
    error-text="This field is required"
  >
    <ion-select-option value="apple">Apple</ion-select-option>
    <ion-select-option value="banana">Banana</ion-select-option>
    <ion-select-option value="orange">Orange</ion-select-option>
  </ion-select>

  <br />

  <ion-button type="submit" size="small">Submit</ion-button>
</form>

<script>
  const form = document.getElementById('my-form');
  const favFruit = form.querySelector('ion-select');

  form.addEventListener('submit', (event) => submit(event));
  favFruit.addEventListener('ionChange', (event) => validateSelect(event));
  favFruit.addEventListener('ionBlur', () => onIonBlur({ detail: { value: favFruit.value } }));

  const validateSelect = (event) => {
    if (!event.detail.value) {
      favFruit.classList.add('ion-invalid');
      favFruit.classList.remove('ion-valid');
    } else {
      favFruit.classList.remove('ion-invalid');
      favFruit.classList.add('ion-valid');
    }
  };

  const markTouched = () => {
    favFruit.classList.add('ion-touched');
  };

  const onIonBlur = (event) => {
    markTouched();
    validateSelect(event);
  };

  const submit = (event) => {
    event.preventDefault();

    markTouched();
    validateSelect({ detail: { value: favFruit.value } });
  };
</script>

Angular

src/app/example.component.html

<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
  <ion-select
    formControlName="favFruit"
    label="Favorite fruit"
    placeholder="Select fruit"
    helperText="Select your favorite fruit"
    errorText="This field is required"
  >
    <ion-select-option value="apple">Apple</ion-select-option>
    <ion-select-option value="banana">Banana</ion-select-option>
    <ion-select-option value="orange">Orange</ion-select-option>
  </ion-select>

  <br />

  <ion-button type="submit" size="small">Submit</ion-button>
</form>

src/app/example.component.ts

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule } from '@angular/forms';
import { IonSelect, IonSelectOption, IonButton } from '@ionic/angular';

@Component({
  selector: 'app-example',
  imports: [IonSelect, IonSelectOption, IonButton, ReactiveFormsModule],
  templateUrl: './example.component.html',
  styleUrl: './example.component.css',
})
export class ExampleComponent {
  myForm: FormGroup;

  constructor(private fb: FormBuilder) {
    this.myForm = this.fb.group({
      favFruit: ['', Validators.required],
    });
  }

  onSubmit() {
    // Mark the control as touched to trigger the error message.
    // This is needed if the user submits the form without interacting
    // with the select.
    this.myForm.get('favFruit')!.markAsTouched();
  }
}

React

import React, { useRef, useState } from 'react';
import { IonSelect, IonSelectOption, IonButton, SelectCustomEvent } from '@ionic/react';

function Example() {
  const [isTouched, setIsTouched] = useState<boolean>(false);
  const [isValid, setIsValid] = useState<boolean | undefined>();

  const favFruitRef = useRef<HTMLIonSelectElement>(null);

  const validateSelect = (event: SelectCustomEvent<{ value: string }>) => {
    setIsValid(event.detail.value ? true : false);
  };

  const markTouched = () => {
    setIsTouched(true);
  };

  const onIonBlur = () => {
    markTouched();

    if (favFruitRef.current) {
      validateSelect({ detail: { value: favFruitRef.current.value } } as SelectCustomEvent<{
        value: string;
      }>);
    }
  };

  const submit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    markTouched();

    if (favFruitRef.current) {
      validateSelect({ detail: { value: favFruitRef.current.value } } as SelectCustomEvent<{
        value: string;
      }>);
    }
  };

  return (
    <>
      <form onSubmit={submit}>
        <IonSelect
          ref={favFruitRef}
          label="Favorite fruit"
          placeholder="Select fruit"
          className={`${isValid ? 'ion-valid' : ''} ${isValid === false ? 'ion-invalid' : ''} ${
            isTouched ? 'ion-touched' : ''
          }`}
          helperText="Select your favorite fruit"
          errorText="This field is required"
          onIonChange={(event) => validateSelect(event)}
          onIonBlur={onIonBlur}
        >
          <IonSelectOption value="apple">Apple</IonSelectOption>
          <IonSelectOption value="banana">Banana</IonSelectOption>
          <IonSelectOption value="orange">Orange</IonSelectOption>
        </IonSelect>

        <br />

        <IonButton type="submit" size="small">
          Submit
        </IonButton>
      </form>
    </>
  );
}

export default Example;

Vue

<template>
  <form @submit.prevent="submit">
    <ion-select
      v-model="favFruit"
      label="Favorite fruit"
      placeholder="Select fruit"
      helper-text="Select your favorite fruit"
      error-text="This field is required"
      @ionChange="validateSelect"
      @ionBlur="onIonBlur"
      :class="{ 'ion-valid': isValid, 'ion-invalid': isValid === false, 'ion-touched': isTouched }"
    >
      <ion-select-option value="apple">Apple</ion-select-option>
      <ion-select-option value="banana">Banana</ion-select-option>
      <ion-select-option value="orange">Orange</ion-select-option>
    </ion-select>

    <br />

    <ion-button type="submit" size="small">Submit</ion-button>
  </form>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { IonSelect, IonSelectOption, IonButton, SelectCustomEvent } from '@ionic/vue';

  const favFruit = ref('');
  const isTouched = ref(false);
  const isValid = ref<boolean | undefined>();

  const validateSelect = (event: SelectCustomEvent<{ value: string }>) => {
    isValid.value = event.detail.value ? true : false;
  };

  const markTouched = () => {
    isTouched.value = true;
  };

  const onIonBlur = () => {
    markTouched();
    validateSelect({ detail: { value: favFruit.value } } as SelectCustomEvent<{ value: string }>);
  };

  const submit = () => {
    markTouched();
    validateSelect({ detail: { value: favFruit.value } } as SelectCustomEvent<{ value: string }>);
  };
</script>

Interfaces

SelectChangeEventDetail

interface SelectChangeEventDetail<T = any> {
  value: T;
}

SelectCustomEvent

필수는 아니지만, 이 컴포넌트에서 내보내는 Ionic 이벤트에 더 강력한 타입 지정을 하려면 CustomEvent 인터페이스 대신 이 인터페이스를 사용할 수 있어요.

interface SelectCustomEvent<T = any> extends CustomEvent {
  detail: SelectChangeEventDetail<T>;
  target: HTMLIonSelectElement;
}

Accessibility

Keyboard Interactions

Ionic의 키보드 상호작용은 모든 플랫폼에서 일관된 경험을 제공하기 위해 네이티브 iOS select 대신 웹의 구현 패턴을 따르고 있어요.

다음 조건이 충족될 때 이러한 키보드 상호작용이 모든 ion-select 요소에 적용돼요:

  • select가 닫혀 있어요.
  • select에 포커스가 있어요.
  • select가 비활성화되지 않았어요.
Key Description
Enter Opens the overlay and focuses on the first selected option. If there is no selected option, then it focuses on the first option.
Space Opens the overlay and focuses on the first selected option. If there is no selected option, then it focuses on the first option.

Single Selection

단일 선택의 키보드 상호작용은 radio의 ARIA 구현 패턴을 따르고 있어요.

이 키보드 상호작용은 오버레이가 표시되고 포커스되어 있을 때 ion-action-sheet, ion-alert, ion-popover, ion-modal 요소에 적용돼요.

Key Description
ArrowDown Focuses and selects the next option in the list. If there is no next option, selection will cycle to the first option.
ArrowLeft Focuses and selects the previous option in the list. If there is no previous option, selection will cycle to the last option.
ArrowRight Focuses and selects the next option in the list. If there is no next option, selection will cycle to the first option.
ArrowUp Focuses and selects the previous option in the list. If there is no previous option, selection will cycle to the last option.
Enter If an option is focused, it will select the option. Overlays without an 'OK' button will commit the value immediately, dismiss the overlay and return focus to the ion-select element. If the 'OK' button is focused, it will save the user's selection, dismiss the overlay and return focus to the ion-select element.
Escape Closes the overlay without changing the submitted option. Returns the focus back to the ion-select element.
Space If the focused radio button is not checked, unchecks the currently checked radio button and checks the focused radio button. Otherwise, does nothing. If the overlay does not have an 'OK' button, the value will be committed immediately and the overlay will dismiss.
Tab Moves focus to the next focusable element (cancel button, 'OK' button, or either the selection or the first option) on the overlay. If the next focusable element is an option, then it will focus on the selected option, otherwise it will focus the first option.

Multiple Selection

다중 선택의 키보드 상호작용은 checkbox의 ARIA 구현 패턴을 따르고 있어요.

이 키보드 상호작용은 오버레이가 표시되고 다중 선택이 활성화되었을 때 ion-alert, ion-popover, ion-modal 요소에 적용돼요.

Key Description
Enter When the 'OK' button is focused, it will save the user's selection, dismiss the overlay, and return focus to the ion-select element.
Escape Closes the overlay without changing the submitted option(s). Returns the focus back to the ion-select element.
Space Selects or deselects the currently focused option. This does not deselect the other selected options. If the overlay does not have an 'OK' button, the value will be committed immediately.
Tab Move focus to the next focusable element (cancel button, 'OK' button, or any of the options) on the overlay. If the next focusable element is the options list, then it should iterate through each option.

Properties

cancelText

Description: 취소 버튼에 표시할 텍스트예요.

Attribute: cancel-text

Type: string

Default: 'Cancel'

color

Description: 애플리케이션의 색상 팔레트에서 사용할 색이에요. 기본 옵션은 "primary", "secondary", "tertiary", "success", "warning", "danger", "light", "medium", "dark"예요. 색상에 대한 자세한 내용은 theming을 참고해 주세요. 이 속성은 모던 select 문법을 사용할 때만 사용할 수 있어요.

Attribute: color

Type: "danger" | "dark" | "light" | "medium" | "primary" | "secondary" | "success" | "tertiary" | "warning" | string | undefined

Default: undefined

compareWith

Description: 이 속성은 ion-select에서 선택된 옵션을 결정할 때 객체를 비교하는 커스텀 함수나 속성 이름을 지정할 수 있게 해 줘요. 지정하지 않으면 기본적으로 엄격한 동등성(===) 비교가 사용돼요.

Attribute: compare-with

Type: ((currentValue: any, compareValue: any) => boolean) | null | string | undefined

Default: undefined

disabled

Description: true로 설정하면 사용자가 select와 상호작용할 수 없어요.

Attribute: disabled

Type: boolean

Default: false

errorText

Description: select 아래에 배치되어 에러가 감지되었을 때 표시되는 텍스트예요.

Attribute: error-text

Type: string | undefined

Default: undefined

expandedIcon

Description: select가 열려 있을 때 표시할 토글 아이콘이에요. 정의하면 md 모드의 아이콘 회전 동작이 비활성화돼요. 정의하지 않으면 select가 열리고 닫힐 때 모두 toggleIcon이 사용돼요.

Attribute: expanded-icon

Type: string | undefined

Default: undefined

fill

Description: 아이템의 채우기(fill) 방식이에요. "solid"면 아이템에 배경이 있고, "outline"이면 아이템이 테두리와 함께 투명해져요. md 모드에서만 사용할 수 있어요.

Attribute: fill

Type: "outline" | "solid" | undefined

Default: undefined

helperText

Description: select 아래에 배치되어 에러가 감지되지 않았을 때 표시되는 텍스트예요.

Attribute: helper-text

Type: string | undefined

Default: undefined

interface

Description: select가 사용할 인터페이스예요: action-sheet, popover, alert, 또는 modal.

Attribute: interface

Type: "action-sheet" | "alert" | "modal" | "popover"

Default: 'alert'

interfaceOptions

Description: alert, action-sheet 또는 popover 인터페이스가 받을 수 있는 추가 옵션이에요. 각 인터페이스의 생성 옵션은 ion-alert docs, ion-action-sheet docs, ion-popover docs, ion-modal docs를 참고해 주세요. Note: interfaceOptions는 alert 인터페이스의 inputs나 buttons를 재정의하지 않아요.

Attribute: interface-options

Type: any

Default: {}

justify

Description: 한 줄 안에서 라벨과 select를 어떻게 배치할지 결정해요. labelPlacement가 "floating" 또는 "stacked"로 설정되어 라벨과 select가 서로 다른 줄에 있을 때는 justify가 적용되지 않아요. "start": 라벨과 select가 LTR에서는 왼쪽, RTL에서는 오른쪽에 나타나요. "end": 라벨과 select가 LTR에서는 오른쪽, RTL에서는 왼쪽에 나타나요. "space-between": 라벨과 select가 줄의 양끝에 나타나고 두 요소 사이에 공간이 생겨요.

Attribute: justify

Type: "end" | "space-between" | "start" | undefined

Default: undefined

label

Description: select와 연결된 보이는 라벨이에요. 평문 텍스트 라벨을 렌더링해야 할 때 사용해요. label 속성과 label 슬롯을 모두 사용하면 label 속성이 우선해요.

Attribute: label

Type: string | undefined

Default: undefined

labelPlacement

Description: select 기준으로 라벨을 어디에 배치할지 결정해요. "start": 라벨이 LTR에서는 select 왼쪽, RTL에서는 오른쪽에 나타나요. "end": 라벨이 LTR에서는 select 오른쪽, RTL에서는 왼쪽에 나타나요. "floating": 라벨이 select에 포커스되거나 값이 있을 때는 작아지고 select 위에 나타나요. 그렇지 않으면 select 위에 나타나요. "stacked": 라벨이 select가 블러 처리되거나 값이 없을 때조차도 항상 작아지고 select 위에 나타나요. "fixed": 라벨이 "start"와 동일하게 동작하지만 고정된 너비가 있다는 점만 달라요. 긴 텍스트는 줄임표("...")로 잘려요. "floating" 또는 "stacked"를 사용할 때에는 value나 placeholder로 select를 초기화하는 것을 권장해요.

Attribute: label-placement

Type: "end" | "fixed" | "floating" | "stacked" | "start" | undefined

Default: 'start'

mode

Description: mode는 어떤 플랫폼 스타일을 사용할지 결정해요. 초기화할 때 한 번 설정되고 첫 렌더링 이후에 값을 바꿔도 업데이트되지 않는 virtual property예요.

Attribute: mode

Type: "ios" | "md"

Default: undefined

multiple

Description: true로 설정하면 select가 여러 값을 받을 수 있어요.

Attribute: multiple

Type: boolean

Default: false

name

Description: 폼 데이터와 함께 제출되는 컨트롤의 이름이에요.

Attribute: name

Type: string

Default: this.inputId

okText

Description: OK 버튼에 표시할 텍스트예요.

Attribute: ok-text

Type: string

Default: 'OK'

placeholder

Description: select가 비어 있을 때 표시할 텍스트예요.

Attribute: placeholder

Type: string | undefined

Default: undefined

required

Description: true로 설정하면 스크린 리더가 필수 필드로 알려줘요. 이 속성은 접근성 목적으로만 동작하며, 값이 유효하지 않아도 폼이 제출되는 것을 막지는 않아요.

Attribute: required

Type: boolean

Default: false

selectedText

Description: 선택된 옵션의 값 대신 표시할 텍스트예요.

Attribute: selected-text

Type: null | string | undefined

Default: undefined

shape

Description: select의 모양이에요. "round"면 테두리 반지름이 커져요.

Attribute: shape

Type: "round" | undefined

Default: undefined

toggleIcon

Description: 사용할 토글 아이콘이에요. ios 모드에서는 chevronExpand, md 모드에서는 caretDownSharp이 기본값이에요.

Attribute: toggle-icon

Type: string | undefined

Default: undefined

value

Description: select의 값이에요.

Attribute: value

Type: any

Default: undefined

Events

Name Description Bubbles
ionBlur Emitted when the select loses focus. true
ionCancel Emitted when the selection is cancelled. true
ionChange Emitted when the value has changed. This event will not emit when programmatically setting the value property. true
ionDismiss Emitted when the overlay is dismissed. true
ionFocus Emitted when the select has focus. true

Methods

open

Description: select 오버레이를 열어요. 오버레이는 ion-select의 interface 속성에 따라 alert, action sheet 또는 popover가 돼요.

Signature: open(event?: UIEvent) => Promise<any>

Parameters: event: 열기를 호출한 사용자 인터페이스 이벤트예요.

CSS Shadow Parts

Name Description
bottom The container element for helper text, error text, and counter.
container The container for the selected text or placeholder.
control The wrapper element containing the label and native select control. When the label is not floating or stacked, this part also contains the dropdown icon.
end The wrapper element for the content in the end slot. When the label is floating or stacked, this part also contains the dropdown icon.
error-text Supporting text displayed beneath the select when the select is invalid and touched.
helper-text Supporting text displayed beneath the select when the select is valid.
icon The select icon container.
label The label text describing the select.
placeholder The text displayed in the select when there is no value.
start The wrapper element for the content in the start slot.
supporting-text Supporting text displayed beneath the select.
text The displayed value of the select.
wrapper The clickable label element that wraps the entire form field (label text, slots, selected values or placeholder, and toggle icons).

CSS Custom Properties

iOS

Name Description
--background Background of the select
--border-color Color of the select border
--border-radius Radius of the select border. A large radius may display unevenly when using fill="outline"; if needed, use shape="round" instead or increase --padding-start.
--border-style Style of the select border
--border-width Width of the select border
--highlight-color-focused The color of the highlight on the select when focused
--highlight-color-invalid The color of the highlight on the select when invalid
--highlight-color-valid The color of the highlight on the select when valid
--highlight-height The height of the highlight on the select. Only applies to md mode.
--padding-bottom Bottom padding of the select
--padding-end Right padding if direction is left-to-right, and left padding if direction is right-to-left of the select
--padding-start Left padding if direction is left-to-right, and right padding if direction is right-to-left of the select
--padding-top Top padding of the select
--placeholder-color Color of the select placeholder text
--placeholder-opacity Opacity of the select placeholder text
--ripple-color The color of the ripple effect on MD mode.
--select-text-gap The gap between elements in the select text.
--select-text-media-border-color The border color of media (icons/images) in the select text.
--select-text-media-border-radius The border radius of media (icons/images) in the select text.
--select-text-media-border-style The border style of media (icons/images) in the select text.
--select-text-media-border-width The border width of media (icons/images) in the select text.
--select-text-media-height The height of media (icons/images) in the select text.
--select-text-media-width The width of media (icons/images) in the select text.

MD

Name Description
--background Background of the select
--border-color Color of the select border
--border-radius Radius of the select border. A large radius may display unevenly when using fill="outline"; if needed, use shape="round" instead or increase --padding-start.
--border-style Style of the select border
--border-width Width of the select border
--highlight-color-focused The color of the highlight on the select when focused
--highlight-color-invalid The color of the highlight on the select when invalid
--highlight-color-valid The color of the highlight on the select when valid
--highlight-height The height of the highlight on the select. Only applies to md mode.
--padding-bottom Bottom padding of the select
--padding-end Right padding if direction is left-to-right, and left padding if direction is right-to-left of the select
--padding-start Left padding if direction is left-to-right, and right padding if direction is right-to-left of the select
--padding-top Top padding of the select
--placeholder-color Color of the select placeholder text
--placeholder-opacity Opacity of the select placeholder text
--ripple-color The color of the ripple effect on MD mode.
--select-text-gap The gap between elements in the select text.
--select-text-media-border-color The border color of media (icons/images) in the select text.
--select-text-media-border-radius The border radius of media (icons/images) in the select text.
--select-text-media-border-style The border style of media (icons/images) in the select text.
--select-text-media-border-width The border width of media (icons/images) in the select text.
--select-text-media-height The height of media (icons/images) in the select text.
--select-text-media-width The width of media (icons/images) in the select text.

Slots

Name Description
end Content to display at the trailing edge of the select.
label The label text to associate with the select. Use the labelPlacement property to control where the label is placed relative to the select. Use this if you need to render a label with custom HTML.
start Content to display at the leading edge of the select.

더 알아보기 (Learn more)

지금까지 ion-select의 주요 기능과 다양한 인터페이스, 커스터마이징 방법까지 살펴봤어요. 폼 검증이나 객체 값 비교가 필요할 때 compareWith와 helperText/errorText가 특히 유용하니 꼭 활용해 보세요. 관련 컴포넌트에 대해서는 Select Option 문서도 함께 참고하면 좋아요.