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

ion-toggle

원문 보기 위키 갱신

ion-toggle은 단일 옵션의 상태를 바꾸는 스위치예요. 눌러서 또는 스와이프해서 켜고 끌 수 있고, checked 속성으로 프로그래밍 방식으로도 확인할 수 있어요. 이 글에서 기본 사용법, 라벨 배치, 정렬, 헬퍼/에러 텍스트, 테마 적용을 살펴볼게요.

출처: 문서

본문

Encapsulation: shadow

Toggle은 단일 옵션의 상태를 변경하는 스위치입니다. 눌러서 또는 스와이프해서 켜고 끌 수 있습니다. Toggle은 checked 속성을 설정해 프로그래밍 방식으로도 확인할 수 있습니다.

기본 사용법

JavaScript

<ion-toggle>Default Toggle</ion-toggle><br /><br />
<ion-toggle checked="true">Checked Toggle</ion-toggle><br /><br />
<ion-toggle disabled="true">Disabled Toggle</ion-toggle><br /><br />
<ion-toggle checked="true" disabled="true">Disabled Checked Toggle</ion-toggle>

Angular

src/app/example.component.html

<ion-toggle>Default Toggle</ion-toggle><br /><br />
<ion-toggle [checked]="true">Checked Toggle</ion-toggle><br /><br />
<ion-toggle [disabled]="true">Disabled Toggle</ion-toggle><br /><br />
<ion-toggle [checked]="true" [disabled]="true">Disabled Checked Toggle</ion-toggle>

src/app/example.component.ts

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

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

React

import React from 'react';
import { IonToggle } from '@ionic/react';

function Example() {
  return (
    <>
      <IonToggle>Default Toggle</IonToggle>
      <br />
      <br />
      <IonToggle checked={true}>Checked Toggle</IonToggle>
      <br />
      <br />
      <IonToggle disabled={true}>Disabled Toggle</IonToggle>
      <br />
      <br />
      <IonToggle checked={true} disabled={true}>
        Disabled Checked Toggle
      </IonToggle>
    </>
  );
}
export default Example;

Vue

<template>
  <ion-toggle>Default Toggle</ion-toggle><br /><br />
  <ion-toggle :checked="true">Checked Toggle</ion-toggle><br /><br />
  <ion-toggle :disabled="true">Disabled Toggle</ion-toggle><br /><br />
  <ion-toggle :checked="true" :disabled="true">Disabled Checked Toggle</ion-toggle>
</template>

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

켜짐/꺼짐 라벨

enableOnOffLabels 속성을 설정하면 Toggle이 켜짐/꺼짐 라벨을 활성화할 수 있습니다. 이는 체크된 토글과 체크되지 않은 토글을 구분하기 쉽게 만들어 주므로 접근성에 중요합니다.

JavaScript

<ion-toggle enable-on-off-labels="true">Enable Notifications</ion-toggle>

Angular

src/app/example.component.html

<ion-toggle [enableOnOffLabels]="true">Enable Notifications</ion-toggle>

src/app/example.component.ts

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

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

React

import React from 'react';
import { IonToggle } from '@ionic/react';

function Example() {
  return <IonToggle enableOnOffLabels={true}>Enable Notifications</IonToggle>;
}
export default Example;

Vue

<template>
  <ion-toggle :enable-on-off-labels="true">Enable Notifications</ion-toggle>
</template>

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

리스트에서의 Toggle

Item과 List 컴포넌트를 사용해 리스트 뷰에서도 Toggle을 사용할 수 있습니다.

JavaScript

<ion-list>
  <ion-item>
    <ion-toggle>Receive Push Notifications</ion-toggle>
  </ion-item>
  <ion-item>
    <ion-toggle>Receive Emails</ion-toggle>
  </ion-item>
  <ion-item>
    <ion-toggle>Receive Text Messages</ion-toggle>
  </ion-item>
</ion-list>

Angular

src/app/example.component.html

<ion-list>
  <ion-item>
    <ion-toggle>Receive Push Notifications</ion-toggle>
  </ion-item>
  <ion-item>
    <ion-toggle>Receive Emails</ion-toggle>
  </ion-item>
  <ion-item>
    <ion-toggle>Receive Text Messages</ion-toggle>
  </ion-item>
</ion-list>

src/app/example.component.ts

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

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

React

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

function Example() {
  return (
    <IonList>
      <IonItem>
        <IonToggle>Receive Push Notifications</IonToggle>
      </IonItem>
      <IonItem>
        <IonToggle>Receive Emails</IonToggle>
      </IonItem>
      <IonItem>
        <IonToggle>Receive Text Messages</IonToggle>
      </IonItem>
    </IonList>
  );
}
export default Example;

Vue

<template>
  <ion-list>
    <ion-item>
      <ion-toggle>Receive Push Notifications</ion-toggle>
    </ion-item>
    <ion-item>
      <ion-toggle>Receive Emails</ion-toggle>
    </ion-item>
    <ion-item>
      <ion-toggle>Receive Text Messages</ion-toggle>
    </ion-item>
  </ion-list>
</template>

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

라벨 배치

개발자는 labelPlacement 속성을 사용해 컨트롤에 상대적으로 라벨이 어떻게 배치되는지 제어할 수 있습니다.

JavaScript

<ion-toggle label-placement="start">Label at the Start</ion-toggle><br /><br />
<ion-toggle label-placement="end">Label at the End</ion-toggle><br /><br />
<ion-toggle label-placement="fixed">Fixed Width Label</ion-toggle><br /><br />
<ion-toggle label-placement="stacked">Stacked Label</ion-toggle>

Angular

src/app/example.component.html

<ion-toggle labelPlacement="start">Label at the Start</ion-toggle><br /><br />
<ion-toggle labelPlacement="end">Label at the End</ion-toggle><br /><br />
<ion-toggle labelPlacement="fixed">Fixed Width Label</ion-toggle><br /><br />
<ion-toggle labelPlacement="stacked">Stacked Label</ion-toggle>

src/app/example.component.ts

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

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

React

import React from 'react';
import { IonToggle } from '@ionic/react';

function Example() {
  return (
    <>
      <IonToggle labelPlacement="start">Label at the Start</IonToggle>
      <br />
      <br />
      <IonToggle labelPlacement="end">Label at the End</IonToggle>
      <br />
      <br />
      <IonToggle labelPlacement="fixed">Fixed Width Label</IonToggle>
      <br />
      <br />
      <IonToggle labelPlacement="stacked">Stacked Label</IonToggle>
    </>
  );
}
export default Example;

Vue

<template>
  <ion-toggle label-placement="start">Label at the Start</ion-toggle><br /><br />
  <ion-toggle label-placement="end">Label at the End</ion-toggle><br /><br />
  <ion-toggle label-placement="fixed">Fixed Width Label</ion-toggle><br /><br />
  <ion-toggle label-placement="stacked">Stacked Label</ion-toggle>
</template>

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

정렬

개발자는 alignment 속성을 사용해 교차 축에서 라벨과 컨트롤이 어떻게 정렬되는지 제어할 수 있습니다. 이 속성은 flexbox의 align-items 속성을 반영합니다.

참고

Stacked 토글은 alignment 속성으로 정렬할 수 있습니다. 라벨과 컨트롤을 가로로 중앙 정렬해야 할 때 유용할 수 있습니다.

JavaScript

<ion-toggle label-placement="stacked" alignment="start">Aligned to the Start</ion-toggle><br /><br />
<ion-toggle label-placement="stacked" alignment="center">Aligned to the Center</ion-toggle>

Angular

src/app/example.component.html

<ion-toggle labelPlacement="stacked" alignment="start">Aligned to the Start</ion-toggle><br /><br />
<ion-toggle labelPlacement="stacked" alignment="center">Aligned to the Center</ion-toggle>

src/app/example.component.ts

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

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

React

import React from 'react';
import { IonToggle } from '@ionic/react';

function Example() {
  return (
    <>
      <IonToggle labelPlacement="stacked" alignment="start">
        Aligned to the Start
      </IonToggle>
      <br />
      <br />
      <IonToggle labelPlacement="stacked" alignment="center">
        Aligned to the Center
      </IonToggle>
    </>
  );
}
export default Example;

Vue

<template>
  <ion-toggle label-placement="stacked" alignment="start">Aligned to the Start</ion-toggle><br /><br />
  <ion-toggle label-placement="stacked" alignment="center">Aligned to the Center</ion-toggle>
</template>

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

배치 (Justification)

개발자는 justify 속성을 사용해 한 줄에서 라벨과 컨트롤이 어떻게 배치되는지 제어할 수 있습니다.

JavaScript

<ion-list>
  <ion-item>
    <ion-toggle justify="start">Packed at the Start of Line</ion-toggle>
  </ion-item>
  <ion-item>
    <ion-toggle justify="end">Packed at the End of Line</ion-toggle>
  </ion-item>
  <ion-item>
    <ion-toggle justify="space-between">Space Between Label and Control</ion-toggle>
  </ion-item>
</ion-list>

Angular

src/app/example.component.html

<ion-list>
  <ion-item>
    <ion-toggle justify="start">Packed at the Start of Line</ion-toggle>
  </ion-item>
  <ion-item>
    <ion-toggle justify="end">Packed at the End of Line</ion-toggle>
  </ion-item>
  <ion-item>
    <ion-toggle justify="space-between">Space Between Label and Control</ion-toggle>
  </ion-item>
</ion-list>

src/app/example.component.ts

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

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

React

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

function Example() {
  return (
    <IonList>
      <IonItem>
        <IonToggle justify="start">Packed at the Start of Line</IonToggle>
      </IonItem>
      <IonItem>
        <IonToggle justify="end">Packed at the End of Line</IonToggle>
      </IonItem>
      <IonItem>
        <IonToggle justify="space-between">Space Between Label and Control</IonToggle>
      </IonItem>
    </IonList>
  );
}
export default Example;

Vue

<template>
  <ion-list>
    <ion-item>
      <ion-toggle justify="start">Packed at the Start of Line</ion-toggle>
    </ion-item>
    <ion-item>
      <ion-toggle justify="end">Packed at the End of Line</ion-toggle>
    </ion-item>
    <ion-item>
      <ion-toggle justify="space-between">Space Between Label and Control</ion-toggle>
    </ion-item>
  </ion-list>
</template>

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

헬퍼 & 에러 텍스트

helperText와 errorText 속성을 사용해 토글 안에서 헬퍼 텍스트와 에러 텍스트를 사용할 수 있습니다. 에러 텍스트는 ion-invalid와 ion-touched 클래스가 ion-toggle에 추가되지 않는 한 표시되지 않습니다. 이는 사용자가 데이터를 입력할 기회를 갖기 전에 에러가 표시되지 않도록 보장합니다.

Angular에서는 폼 검증을 통해 자동으로 처리됩니다. JavaScript, React, Vue에서는 자체 검증에 기반해 클래스를 수동으로 추가해야 합니다.

JavaScript

<ion-toggle
  helper-text="Enable to connect to available networks"
  error-text="Must be enabled to access the internet"
  justify="space-between"
  checked
>
  Wi-Fi
</ion-toggle>

<script>
  const wifi = document.querySelector('ion-toggle');

  wifi.addEventListener('ionChange', (event) => validateToggle(event));

  const validateToggle = (event) => {
    wifi.classList.add('ion-touched');

    if (!event.detail.checked) {
      wifi.classList.add('ion-invalid');
      wifi.classList.remove('ion-valid');
    } else {
      wifi.classList.remove('ion-invalid');
      wifi.classList.add('ion-valid');
    }
  };
</script>

Angular

src/app/example.component.html

<form [formGroup]="myForm">
  <ion-toggle
    formControlName="wifi"
    helperText="Enable to connect to available networks"
    errorText="Must be enabled to access the internet"
    justify="space-between"
    (ionChange)="onChange()"
  >
    Wi-Fi
  </ion-toggle>
</form>

src/app/example.component.ts

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

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

  constructor(private fb: FormBuilder) {
    this.myForm = this.fb.group({
      wifi: [true, Validators.requiredTrue],
    });
  }

  onChange() {
    // Mark the control as touched to trigger the error message
    // without requiring the toggle to be blurred first
    this.myForm.get('wifi')!.markAsTouched();
  }
}

React

import React, { useRef, useState } from 'react';
import { IonToggle, ToggleCustomEvent } from '@ionic/react';

function Example() {
  const wifiRef = useRef<HTMLIonToggleElement>(null);

  const [isTouched, setIsTouched] = useState<boolean>(false);
  const [isValid, setIsValid] = useState<boolean | undefined>();
  const [isChecked, setIsChecked] = useState<boolean>(true);

  const validateToggle = (event: ToggleCustomEvent<{ checked: boolean }>) => {
    setIsTouched(true);
    setIsChecked(event.detail.checked);
    setIsValid(event.detail.checked);
  };

  return (
    <>
      <IonToggle
        ref={wifiRef}
        className={`${isValid ? 'ion-valid' : ''} ${isValid === false ? 'ion-invalid' : ''} ${
          isTouched ? 'ion-touched' : ''
        }`}
        helperText="Enable to connect to available networks"
        errorText="Must be enabled to access the internet"
        justify="space-between"
        checked={isChecked}
        onIonChange={(event) => validateToggle(event)}
      >
        Wi-Fi
      </IonToggle>
    </>
  );
}

export default Example;

Vue

<template>
  <ion-toggle
    v-model="wifi"
    helper-text="Enable to connect to available networks"
    error-text="Must be enabled to access the internet"
    justify="space-between"
    @ionChange="validateToggle"
    :class="{
      'ion-valid': isValid,
      'ion-invalid': isValid === false,
      'ion-touched': isTouched,
    }"
  >
    Wi-Fi
  </ion-toggle>
</template>

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

  const wifi = ref(true);
  const isTouched = ref(false);
  const isValid = ref<boolean | undefined>();

  const validateToggle = (event: ToggleCustomEvent<{ checked: boolean }>) => {
    isTouched.value = true;
    isValid.value = event.detail.checked;
  };
</script>

테마 적용

색상

JavaScript

<ion-toggle aria-label="Primary toggle" color="primary" checked="true"></ion-toggle>
<ion-toggle aria-label="Secondary toggle" color="secondary" checked="true"></ion-toggle>
<ion-toggle aria-label="Tertiary toggle" color="tertiary" checked="true"></ion-toggle>
<ion-toggle aria-label="Success toggle" color="success" checked="true"></ion-toggle>
<ion-toggle aria-label="Warning toggle" color="warning" checked="true"></ion-toggle>
<ion-toggle aria-label="Danger toggle" color="danger" checked="true"></ion-toggle>
<ion-toggle aria-label="Light toggle" color="light" checked="true"></ion-toggle>
<ion-toggle aria-label="Medium toggle" color="medium" checked="true"></ion-toggle>
<ion-toggle aria-label="Dark toggle" color="dark" checked="true"></ion-toggle>

Angular

src/app/example.component.html

<ion-toggle aria-label="Primary toggle" color="primary" [checked]="true"></ion-toggle>
<ion-toggle aria-label="Secondary toggle" color="secondary" [checked]="true"></ion-toggle>
<ion-toggle aria-label="Tertiary toggle" color="tertiary" [checked]="true"></ion-toggle>
<ion-toggle aria-label="Success toggle" color="success" [checked]="true"></ion-toggle>
<ion-toggle aria-label="Warning toggle" color="warning" [checked]="true"></ion-toggle>
<ion-toggle aria-label="Danger toggle" color="danger" [checked]="true"></ion-toggle>
<ion-toggle aria-label="Light toggle" color="light" [checked]="true"></ion-toggle>
<ion-toggle aria-label="Medium toggle" color="medium" [checked]="true"></ion-toggle>
<ion-toggle aria-label="Dark toggle" color="dark" [checked]="true"></ion-toggle>

src/app/example.component.ts

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

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

React

import React from 'react';
import { IonToggle } from '@ionic/react';

function Example() {
  return (
    <>
      <IonToggle aria-label="Primary toggle" color="primary" checked={true}></IonToggle>
      <IonToggle aria-label="Secondary toggle" color="secondary" checked={true}></IonToggle>
      <IonToggle aria-label="Tertiary toggle" color="tertiary" checked={true}></IonToggle>
      <IonToggle aria-label="Success toggle" color="success" checked={true}></IonToggle>
      <IonToggle aria-label="Warning toggle" color="warning" checked={true}></IonToggle>
      <IonToggle aria-label="Danger toggle" color="danger" checked={true}></IonToggle>
      <IonToggle aria-label="Light toggle" color="light" checked={true}></IonToggle>
      <IonToggle aria-label="Medium toggle" color="medium" checked={true}></IonToggle>
      <IonToggle aria-label="Dark toggle" color="dark" checked={true}></IonToggle>
    </>
  );
}
export default Example;

Vue

<template>
  <ion-toggle aria-label="Primary toggle" color="primary" :checked="true"></ion-toggle>
  <ion-toggle aria-label="Secondary toggle" color="secondary" :checked="true"></ion-toggle>
  <ion-toggle aria-label="Tertiary toggle" color="tertiary" :checked="true"></ion-toggle>
  <ion-toggle aria-label="Success toggle" color="success" :checked="true"></ion-toggle>
  <ion-toggle aria-label="Warning toggle" color="warning" :checked="true"></ion-toggle>
  <ion-toggle aria-label="Danger toggle" color="danger" :checked="true"></ion-toggle>
  <ion-toggle aria-label="Light toggle" color="light" :checked="true"></ion-toggle>
  <ion-toggle aria-label="Medium toggle" color="medium" :checked="true"></ion-toggle>
  <ion-toggle aria-label="Dark toggle" color="dark" :checked="true"></ion-toggle>
</template>

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

CSS 사용자 정의 속성

CSS 사용자 정의 속성은 표준 CSS와 결합해 토글의 다른 부분을 대상으로 지정할 수 있습니다. 토글의 width와 height를 직접 수정해 트랙의 크기를 변경할 수 있고, --handle-width와 --handle-height 사용자 정의 속성을 사용해 핸들 크기를 커스터마이즈할 수 있습니다.

JavaScript

<ion-toggle aria-label="Enable Notifications"></ion-toggle>
<ion-toggle checked="true" aria-label="Enable Notifications"></ion-toggle>

<style>
  ion-toggle {
    padding: 12px;

    --track-background: #ddd;
    --track-background-checked: #ddd;

    --handle-background: #eb7769;
    --handle-background-checked: #95c34e;

    --handle-width: 25px;
    --handle-height: 27px;
    --handle-max-height: auto;
    --handle-spacing: 6px;

    --handle-border-radius: 4px;
    --handle-box-shadow: none;
  }

  ion-toggle::part(track) {
    height: 10px;
    width: 65px;

    /* Required for iOS handle to overflow the height of the track */
    overflow: visible;
  }
</style>

Angular

src/app/example.component.html

<ion-toggle aria-label="Enable Notifications"></ion-toggle>
<ion-toggle [checked]="true" aria-label="Enable Notifications"></ion-toggle>

src/app/example.component.css

ion-toggle {
  padding: 12px;

  --track-background: #ddd;
  --track-background-checked: #ddd;

  --handle-background: #eb7769;
  --handle-background-checked: #95c34e;

  --handle-width: 25px;
  --handle-height: 27px;
  --handle-max-height: auto;
  --handle-spacing: 6px;

  --handle-border-radius: 4px;
  --handle-box-shadow: none;
}

ion-toggle::part(track) {
  height: 10px;
  width: 65px;

  /* Required for iOS handle to overflow the height of the track */
  overflow: visible;
}

src/app/example.component.ts

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

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

React

src/main.css

ion-toggle {
  padding: 12px;

  --track-background: #ddd;
  --track-background-checked: #ddd;

  --handle-background: #eb7769;
  --handle-background-checked: #95c34e;

  --handle-width: 25px;
  --handle-height: 27px;
  --handle-max-height: auto;
  --handle-spacing: 6px;

  --handle-border-radius: 4px;
  --handle-box-shadow: none;
}

ion-toggle::part(track) {
  height: 10px;
  width: 65px;

  /* Required for iOS handle to overflow the height of the track */
  overflow: visible;
}

src/main.tsx

import React from 'react';
import { IonToggle } from '@ionic/react';

import './main.css';

function Example() {
  return (
    <>
      <IonToggle aria-label="Enable Notifications"></IonToggle>
      <IonToggle checked={true} aria-label="Enable Notifications"></IonToggle>
    </>
  );
}
export default Example;

Vue

<template>
  <ion-toggle aria-label="Enable Notifications"></ion-toggle>
  <ion-toggle :checked="true" aria-label="Enable Notifications"></ion-toggle>
</template>

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

<style scoped>
  ion-toggle {
    padding: 12px;

    --track-background: #ddd;
    --track-background-checked: #ddd;

    --handle-background: #eb7769;
    --handle-background-checked: #95c34e;

    --handle-width: 25px;
    --handle-height: 27px;
    --handle-max-height: auto;
    --handle-spacing: 6px;

    --handle-border-radius: 4px;
    --handle-box-shadow: none;
  }

  ion-toggle::part(track) {
    height: 10px;
    width: 65px;

    /* Required for iOS handle to overflow the height of the track */
    overflow: visible;
  }
</style>

CSS Shadow Parts

노출된 특정 shadow parts를 대상으로 지정해 토글을 더욱 커스터마이즈할 수 있습니다. 이 parts의 모든 CSS 속성을 스타일링할 수 있고, CSS 사용자 정의 속성과도 결합할 수 있습니다.

JavaScript

<ion-toggle aria-label="Enable Notifications"></ion-toggle>
<ion-toggle checked="true" aria-label="Enable Notifications"></ion-toggle>

<style>
  ion-toggle {
    padding: 12px;

    --handle-width: 25px;
    --handle-height: 27px;
    --handle-max-height: auto;
    --handle-spacing: 6px;

    contain: none;
  }

  ion-toggle::part(track),
  ion-toggle.toggle-checked::part(track) {
    height: 10px;
    width: 65px;

    background: #ddd;

    /* Required for iOS handle to overflow the height of the track */
    overflow: visible;
  }

  ion-toggle::part(handle) {
    background: #eb7769;

    border-radius: 4px;
    box-shadow: none;
  }

  ion-toggle.toggle-checked::part(handle) {
    background: #95c34e;
  }
</style>

Angular

src/app/example.component.html

<ion-toggle aria-label="Enable Notifications"></ion-toggle>
<ion-toggle [checked]="true" aria-label="Enable Notifications"></ion-toggle>

src/app/example.component.css

ion-toggle {
  padding: 12px;

  --handle-width: 25px;
  --handle-height: 27px;
  --handle-max-height: auto;
  --handle-spacing: 6px;

  contain: none;
}

ion-toggle::part(track),
ion-toggle.toggle-checked::part(track) {
  height: 10px;
  width: 65px;

  background: #ddd;

  /* Required for iOS handle to overflow the height of the track */
  overflow: visible;
}

ion-toggle::part(handle) {
  background: #eb7769;

  border-radius: 4px;
  box-shadow: none;
}

ion-toggle.toggle-checked::part(handle) {
  background: #95c34e;
}

src/app/example.component.ts

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

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

React

src/main.css

ion-toggle {
  padding: 12px;

  --handle-width: 25px;
  --handle-height: 27px;
  --handle-max-height: auto;
  --handle-spacing: 6px;

  contain: none;
}

ion-toggle::part(track),
ion-toggle.toggle-checked::part(track) {
  height: 10px;
  width: 65px;

  background: #ddd;

  /* Required for iOS handle to overflow the height of the track */
  overflow: visible;
}

ion-toggle::part(handle) {
  background: #eb7769;

  border-radius: 4px;
  box-shadow: none;
}

ion-toggle.toggle-checked::part(handle) {
  background: #95c34e;
}

src/main.tsx

import React from 'react';
import { IonToggle } from '@ionic/react';

import './main.css';

function Example() {
  return (
    <>
      <IonToggle aria-label="Enable Notifications"></IonToggle>
      <IonToggle checked={true} aria-label="Enable Notifications"></IonToggle>
    </>
  );
}
export default Example;

Vue

<template>
  <ion-toggle aria-label="Enable Notifications"></ion-toggle>
  <ion-toggle :checked="true" aria-label="Enable Notifications"></ion-toggle>
</template>

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

<style scoped>
  ion-toggle {
    padding: 12px;

    --handle-width: 25px;
    --handle-height: 27px;
    --handle-max-height: auto;
    --handle-spacing: 6px;

    contain: none;
  }

  ion-toggle::part(track),
  ion-toggle.toggle-checked::part(track) {
    height: 10px;
    width: 65px;

    background: #ddd;

    /* Required for iOS handle to overflow the height of the track */
    overflow: visible;
  }

  ion-toggle::part(handle) {
    background: #eb7769;

    border-radius: 4px;
    box-shadow: none;
  }

  ion-toggle.toggle-checked::part(handle) {
    background: #95c34e;
  }
</style>

인터페이스

ToggleChangeEventDetail

interface ToggleChangeEventDetail<T = any> {
  value: T;
  checked: boolean;
}

ToggleCustomEvent

필수는 아니지만, 이 인터페이스를 CustomEvent 인터페이스 대신 사용해 이 컴포넌트에서 발생된 Ionic 이벤트에 더 강한 타입을 제공할 수 있습니다.

interface ToggleCustomEvent<T = any> extends CustomEvent {
  detail: ToggleChangeEventDetail<T>;
  target: HTMLIonToggleElement;
}

속성 (Properties)

alignment

설명: 교차 축에서 토글과 라벨의 정렬을 제어하는 방법입니다. "start": 라벨과 컨트롤이 LTR에서는 교차 축의 왼쪽에, RTL에서는 오른쪽에 나타납니다. "center": 라벨과 컨트롤이 LTR과 RTL 모두에서 교차 축의 중앙에 나타납니다. 이 속성을 설정하면 토글 display가 block으로 변경됩니다.

속성: alignment

타입: "center" | "start" | undefined

기본값: undefined

checked

설명: true이면 토글이 선택됩니다.

속성: checked

타입: boolean

기본값: false

color

설명: 애플리케이션의 색상 팔레트에서 사용할 색상입니다. 기본 옵션은 "primary", "secondary", "tertiary", "success", "warning", "danger", "light", "medium", "dark"입니다. 색상에 대한 자세한 내용은 테마를 참조하세요.

속성: color

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

기본값: undefined

disabled

설명: true이면 사용자가 토글과 상호작용할 수 없습니다.

속성: disabled

타입: boolean

기본값: false

enableOnOffLabels

설명: 토글 안에서 켜짐/꺼짐 접근성 스위치 라벨을 활성화합니다.

속성: enable-on-off-labels

타입: boolean | undefined

기본값: config.get('toggleOnOffLabels')

errorText

설명: 토글 라벨 아래에 배치되고 에러가 감지되었을 때 표시되는 텍스트입니다.

속성: error-text

타입: string | undefined

기본값: undefined

helperText

설명: 토글 라벨 아래에 배치되고 에러가 감지되지 않았을 때 표시되는 텍스트입니다.

속성: helper-text

타입: string | undefined

기본값: undefined

justify

설명: 한 줄 안에서 라벨과 토글을 배치하는 방법입니다. "start": 라벨과 토글이 LTR에서는 왼쪽에, RTL에서는 오른쪽에 나타납니다. "end": 라벨과 토글이 LTR에서는 오른쪽에, RTL에서는 왼쪽에 나타납니다. "space-between": 라벨과 토글이 두 요소 사이에 공간을 두고 줄의 반대쪽 끝에 나타납니다. 이 속성을 설정하면 토글 display가 block으로 변경됩니다.

속성: justify

타입: "end" | "space-between" | "start" | undefined

기본값: undefined

labelPlacement

설명: 입력에 상대적으로 라벨을 배치할 위치입니다. "start": 라벨이 LTR에서는 토글 왼쪽에, RTL에서는 오른쪽에 나타납니다. "end": 라벨이 LTR에서는 토글 오른쪽에, RTL에서는 왼쪽에 나타납니다. "fixed": 라벨은 "start"와 같은 동작을 하지만 고정 너비를 가집니다. 긴 텍스트는 줄임표("...")로 잘립니다. "stacked": 라벨이 방향과 관계없이 토글 위에 나타납니다. 라벨의 정렬은 alignment 속성으로 제어할 수 있습니다.

속성: label-placement

타입: "end" | "fixed" | "stacked" | "start"

기본값: 'start'

mode

설명: mode는 사용할 플랫폼 스타일을 결정합니다. 이것은 초기화 중에 한 번 설정되고 초기 렌더 후 값을 변경해도 업데이트되지 않는 가상 속성입니다.

속성: mode

타입: "ios" | "md"

기본값: undefined

name

설명: 폼 데이터와 함께 제출되는 컨트롤의 이름입니다.

속성: name

타입: string

기본값: this.inputId

required

설명: true이면 스크린 리더가 필수 필드로 안내합니다. 이 속성은 접근성 목적으로만 동작하며, 값이 유효하지 않더라도 폼이 제출되는 것을 막지는 않습니다.

속성: required

타입: boolean

기본값: false

value

설명: 토글의 값은 체크되었는지 여부를 의미하지 않으며, 그것에는 checked 속성을 사용하세요. 토글의 값은 <input type="checkbox">의 값과 유사하며, 토글이 네이티브 <form>에 참여할 때만 사용됩니다.

속성: value

타입: null | string | undefined

기본값: 'on'

이벤트

Name Description Bubbles
ionBlur 토글이 포커스를 잃었을 때 발생합니다. true
ionChange 사용자가 토글을 켜거나 껐을 때 발생합니다. 이 이벤트는 checked 속성을 프로그래밍 방식으로 설정할 때는 발생하지 않습니다. true
ionFocus 토글이 포커스를 가졌을 때 발생합니다. true

메서드

이 컴포넌트에 공개 메서드가 없습니다.

CSS Shadow Parts

Name Description
error-text 토글이 유효하지 않고 touched 되었을 때 토글 라벨 아래에 표시되는 보조 텍스트.
handle 체크 상태를 변경하는 데 사용되는 토글 핸들 또는 노브.
helper-text 토글이 유효할 때 토글 라벨 아래에 표시되는 보조 텍스트.
label 토글을 설명하는 라벨 텍스트.
supporting-text 토글 라벨 아래에 표시되는 보조 텍스트.
track 토글의 배경 트랙.

CSS 사용자 정의 속성

iOS

Name Description
--border-radius 토글 트랙의 테두리 반경
--handle-background 토글 핸들의 배경
--handle-background-checked 체크되었을 때 토글 핸들의 배경
--handle-border-radius 토글 핸들의 테두리 반경
--handle-box-shadow 토글 핸들의 박스 그림자
--handle-height 토글 핸들의 높이
--handle-max-height 토글 핸들의 최대 높이
--handle-spacing 토글 핸들 주변의 가로 간격
--handle-transition 토글 핸들의 전환
--handle-width 토글 핸들의 너비
--track-background 토글 트랙의 배경
--track-background-checked 체크되었을 때 토글 트랙의 배경

MD

Name Description
--border-radius 토글 트랙의 테두리 반경
--handle-background 토글 핸들의 배경
--handle-background-checked 체크되었을 때 토글 핸들의 배경
--handle-border-radius 토글 핸들의 테두리 반경
--handle-box-shadow 토글 핸들의 박스 그림자
--handle-height 토글 핸들의 높이
--handle-max-height 토글 핸들의 최대 높이
--handle-spacing 토글 핸들 주변의 가로 간격
--handle-transition 토글 핸들의 전환
--handle-width 토글 핸들의 너비
--track-background 토글 트랙의 배경
--track-background-checked 체크되었을 때 토글 트랙의 배경

슬롯

Name Description
토글과 연결할 라벨 텍스트. 라벨이 토글에 상대적으로 어디에 배치될지는 "labelPlacement" 속성으로 제어하세요.

더 알아보기 (Learn more)

ion-toggle은 단일 선택 상태를 다루는 스위치 컴포넌트예요. 라벨 배치(labelPlacement), 정렬(alignment), 배치(justify), 켜짐/꺼짐 라벨(enableOnOffLabels)을 조합하면 다양한 폼 UI를 만들 수 있고, --track-*/--handle-* CSS 변수로 트랙과 핸들을 세밀하게 꾸밀 수 있어요.