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

ion-textarea

원문 보기 위키 갱신

여러 줄 텍스트 입력에 사용하는 컴포넌트인 ion-textarea예요. 컴포넌트 안쪽에는 네이티브 textarea 요소가 렌더링되며, 네이티브 textarea를 제어하면서 사용자 경험과 상호작용성을 개선해요. 네이티브 textarea와 달리 Ionic textarea는 내부 콘텐츠에서 값을 불러오지 않으니 값을 value 속성으로 설정해야 해요.

출처: 문서

본문

Encapsulation: scoped

Textarea 컴포넌트는 여러 줄 텍스트 입력에 사용돼요. 컴포넌트 내부에는 네이티브 textarea 요소가 렌더링돼요. 네이티브 textarea를 제어할 수 있다는 점 덕분에 textarea 컴포넌트의 사용자 경험과 상호작용성이 향상돼요.

네이티브 textarea 요소와 달리 Ionic textarea는 내부 콘텐츠에서 값을 불러오는 것을 지원하지 않아요. textarea의 값은 value 속성에 설정해야 해요.

Textarea 컴포넌트는 Ionic 프로퍼티 외에도 native textarea attributes를 받아들여요.

Basic Usage

JavaScript

<ion-list>
  <ion-item>
    <ion-textarea label="Regular textarea" placeholder="Type something here"></ion-textarea>
  </ion-item>
  <ion-item>
    <ion-textarea readonly="true" label="Readonly textarea" placeholder="Can't edit this"></ion-textarea>
  </ion-item>
  <ion-item>
    <ion-textarea disabled="true" label="Disabled textarea" placeholder="Can't type here"></ion-textarea>
  </ion-item>
</ion-list>

Angular

src/app/example.component.html

<ion-list>
  <ion-item>
    <ion-textarea label="Regular textarea" placeholder="Type something here"></ion-textarea>
  </ion-item>
  <ion-item>
    <ion-textarea [readonly]="true" label="Readonly textarea" placeholder="Can't edit this"></ion-textarea>
  </ion-item>
  <ion-item>
    <ion-textarea [disabled]="true" label="Disabled textarea" placeholder="Can't type here"></ion-textarea>
  </ion-item>
</ion-list>

src/app/example.component.ts

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

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

React

import React from 'react';
import { IonItem, IonList, IonTextarea } from '@ionic/react';
function Example() {
  return (
    <IonList>
      <IonItem>
        <IonTextarea label="Regular textarea" placeholder="Type something here"></IonTextarea>
      </IonItem>
      <IonItem>
        <IonTextarea readonly={true} label="Readonly textarea" placeholder="Can't edit this"></IonTextarea>
      </IonItem>
      <IonItem>
        <IonTextarea disabled={true} label="Disabled textarea" placeholder="Can't type here"></IonTextarea>
      </IonItem>
    </IonList>
  );
}
export default Example;

Vue

<template>
  <ion-list>
    <ion-item>
      <ion-textarea label="Regular textarea" placeholder="Type something here"></ion-textarea>
    </ion-item>
    <ion-item>
      <ion-textarea :readonly="true" label="Readonly textarea" placeholder="Can't edit this"></ion-textarea>
    </ion-item>
    <ion-item>
      <ion-textarea :disabled="true" label="Disabled textarea" placeholder="Can't type here"></ion-textarea>
    </ion-item>
  </ion-list>
</template>

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

Labels

라벨은 textarea를 설명하는 데 사용해야 해요. 라벨은 시각적으로 활용할 수 있고, 사용자가 textarea에 포커스했을 때 화면 판독기가 라벨을 읽어 주기도 해요. 이렇게 하면 사용자가 textarea의 용도를 쉽게 이해할 수 있어요. Textarea에 라벨을 지정하는 방법은 여러 가지예요:

  • label 프로퍼티: 일반 텍스트 라벨에 사용해요
  • label 슬롯: 커스텀 HTML 라벨에 사용해요 (실험적)
  • aria-label: 화면 판독기용 라벨을 제공하지만 눈에 보이는 라벨은 추가하지 않아요

Label Placement

라벨은 기본적으로 콘텐츠의 너비를 차지해요. 개발자는 labelPlacement 프로퍼티를 사용해 라벨이 제어 요소 기준으로 어떻게 배치될지 제어할 수 있어요.

JavaScript

<ion-list>
  <ion-item>
    <ion-textarea label="Default label" placeholder="Enter text"></ion-textarea>
  </ion-item>
  <ion-item>
    <ion-textarea label="Fixed label" label-placement="fixed" placeholder="Enter text"></ion-textarea>
  </ion-item>
  <ion-item>
    <ion-textarea label="Stacked label" label-placement="stacked" placeholder="Enter text"></ion-textarea>
  </ion-item>
  <ion-item>
    <ion-textarea label="Floating label" label-placement="floating" placeholder="Enter text"></ion-textarea>
  </ion-item>
</ion-list>

Angular

src/app/example.component.html

<ion-list>
  <ion-item>
    <ion-textarea label="Default label" placeholder="Enter text"></ion-textarea>
  </ion-item>
  <ion-item>
    <ion-textarea label="Fixed label" labelPlacement="fixed" placeholder="Enter text"></ion-textarea>
  </ion-item>
  <ion-item>
    <ion-textarea label="Stacked label" labelPlacement="stacked" placeholder="Enter text"></ion-textarea>
  </ion-item>
  <ion-item>
    <ion-textarea label="Floating label" labelPlacement="floating" placeholder="Enter text"></ion-textarea>
  </ion-item>
</ion-list>

src/app/example.component.ts

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

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

React

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

function Example() {
  return (
    <IonList>
      <IonItem>
        <IonTextarea label="Default label" placeholder="Enter text"></IonTextarea>
      </IonItem>
      <IonItem>
        <IonTextarea label="Fixed label" labelPlacement="fixed" placeholder="Enter text"></IonTextarea>
      </IonItem>
      <IonItem>
        <IonTextarea label="Stacked label" labelPlacement="stacked" placeholder="Enter text"></IonTextarea>
      </IonItem>
      <IonItem>
        <IonTextarea label="Floating label" labelPlacement="floating" placeholder="Enter text"></IonTextarea>
      </IonItem>
    </IonList>
  );
}
export default Example;

Vue

<template>
  <ion-list>
    <ion-item>
      <ion-textarea label="Default label" placeholder="Enter text"></ion-textarea>
    </ion-item>
    <ion-item>
      <ion-textarea label="Fixed label" label-placement="fixed" placeholder="Enter text"></ion-textarea>
    </ion-item>
    <ion-item>
      <ion-textarea label="Stacked label" label-placement="stacked" placeholder="Enter text"></ion-textarea>
    </ion-item>
    <ion-item>
      <ion-textarea label="Floating label" label-placement="floating" placeholder="Enter text"></ion-textarea>
    </ion-item>
  </ion-list>
</template>

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

Label Slot (experimental)

일반 텍스트 라벨은 label 프로퍼티로 전달해야 하지만, 커스텀 HTML이 필요하다면 대신 label 슬롯을 통해 전달할 수 있어요.

이 기능은 Web Component slots의 시뮬레이션 버전에 의존하기 때문에 실험적인 것으로 간주돼요. 그 결과 시뮬레이션된 동작이 네이티브 슬롯 동작과 정확히 일치하지 않을 수 있어요.

JavaScript

<ion-list>
  <ion-item>
    <ion-textarea label-placement="floating" value="Lorem Ipsum">
      <div slot="label">Comments <ion-text color="danger">(Required)</ion-text></div>
    </ion-textarea>
  </ion-item>
</ion-list>

Angular

src/app/example.component.html

<ion-list>
  <ion-item>
    <ion-textarea labelPlacement="floating" value="Lorem Ipsum">
      <div slot="label">Comments <ion-text color="danger">(Required)</ion-text></div>
    </ion-textarea>
  </ion-item>
</ion-list>

src/app/example.component.ts

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

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

React

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

function Example() {
  return (
    <IonList>
      <IonItem>
        <IonTextarea labelPlacement="floating" value="Lorem Ipsum">
          <div slot="label">
            Comments <IonText color="danger">(Required)</IonText>
          </div>
        </IonTextarea>
      </IonItem>
    </IonList>
  );
}
export default Example;

Vue

<template>
  <ion-list>
    <ion-item>
      <ion-textarea label-placement="floating" value="Lorem Ipsum">
        <div slot="label">Comments <ion-text color="danger">(Required)</ion-text></div>
      </ion-textarea>
    </ion-item>
  </ion-list>
</template>

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

No Visible Label

눈에 보이는 라벨이 필요 없다면 화면 판독기가 textarea에 접근할 수 있도록 개발자는 여전히 aria-label을 제공해야 해요.

JavaScript

<ion-list>
  <ion-item>
    <ion-textarea aria-label="Comments" value="Lorem Ipsum"></ion-textarea>
  </ion-item>
</ion-list>

Angular

src/app/example.component.html

<ion-list>
  <ion-item>
    <ion-textarea aria-label="Comments" value="Lorem Ipsum"></ion-textarea>
  </ion-item>
</ion-list>

src/app/example.component.ts

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

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

React

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

function Example() {
  return (
    <IonList>
      <IonItem>
        <IonTextarea aria-label="Comments" value="Lorem Ipsum"></IonTextarea>
      </IonItem>
    </IonList>
  );
}
export default Example;

Vue

<template>
  <ion-list>
    <ion-item>
      <ion-textarea aria-label="Comments" value="Lorem Ipsum"></ion-textarea>
    </ion-item>
  </ion-list>
</template>

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

Filled Textareas

Material Design은 textarea에 채워진(filled) 스타일을 제공해요. item의 fill 프로퍼티를 "solid" 또는 "outline"으로 설정할 수 있어요.

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

Warning

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

JavaScript

<ion-textarea label="Solid textarea" label-placement="floating" fill="solid" placeholder="Enter text"></ion-textarea>

<br />

<ion-textarea
  label="Outline textarea"
  label-placement="floating"
  fill="outline"
  placeholder="Enter text"
></ion-textarea>

Angular

src/app/example.component.html

<ion-textarea label="Solid textarea" labelPlacement="floating" fill="solid" placeholder="Enter text"></ion-textarea>

<br />

<ion-textarea label="Outline textarea" labelPlacement="floating" fill="outline" placeholder="Enter text"></ion-textarea>

src/app/example.component.ts

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

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

React

import React from 'react';
import { IonTextarea } from '@ionic/react';
function Example() {
  return (
    <>
      <IonTextarea label="Solid textarea" labelPlacement="floating" fill="solid" placeholder="Enter text"></IonTextarea>

      <br />

      <IonTextarea
        label="Outline textarea"
        labelPlacement="floating"
        fill="outline"
        placeholder="Enter text"
      ></IonTextarea>
    </>
  );
}
export default Example;

Vue

<template>
  <ion-textarea label="Solid textarea" label-placement="floating" fill="solid" placeholder="Enter text"></ion-textarea>

  <br />

  <ion-textarea
    label="Outline textarea"
    label-placement="floating"
    fill="outline"
    placeholder="Enter text"
  ></ion-textarea>
</template>

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

Helper & Error Text

Helper text와 error text는 helperText와 errorText 프로퍼티로 textarea 안에서 사용할 수 있어요. ion-invalid와 ion-touched 클래스가 ion-textarea에 추가되지 않으면 error text는 표시되지 않아요. 이렇게 하면 사용자가 데이터를 입력할 기회를 갖기 전에 오류가 표시되지 않도록 보장해요.

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

JavaScript

<ion-textarea
  fill="solid"
  label="Email"
  label-placement="floating"
  helper-text="Enter a valid email"
  error-text="Invalid email"
></ion-textarea>

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

  textarea.addEventListener('ionInput', (event) => validate(event));
  textarea.addEventListener('ionBlur', () => markTouched());

  const validateEmail = (email) => {
    return email.match(
      /^(?=.{1,254}$)(?=.{1,64}@)[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
    );
  };

  const validate = (event) => {
    const value = event.target.value;

    textarea.classList.remove('ion-valid');
    textarea.classList.remove('ion-invalid');

    if (value === '') return;

    validateEmail(value) ? textarea.classList.add('ion-valid') : textarea.classList.add('ion-invalid');
  };

  const markTouched = () => {
    textarea.classList.add('ion-touched');
  };
</script>

Angular

src/app/example.component.html

<ion-textarea
  fill="solid"
  label="Email"
  labelPlacement="floating"
  helperText="Enter a valid email"
  errorText="Invalid email"
  ngModel
  email
></ion-textarea>

src/app/example.component.ts

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

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

React

import React, { useState } from 'react';
import { clsx } from 'clsx';

import { IonTextarea } from '@ionic/react';

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

  const validateEmail = (email: string) => {
    return email.match(
      /^(?=.{1,254}$)(?=.{1,64}@)[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
    );
  };

  const validate = (event: Event) => {
    const value = (event.target as HTMLTextAreaElement).value;

    setIsValid(undefined);

    if (value === '') return;

    validateEmail(value) !== null ? setIsValid(true) : setIsValid(false);
  };

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

  return (
    <IonTextarea
      className={clsx({
        'ion-valid': isValid,
        'ion-invalid': isValid === false,
        'ion-touched': isTouched,
      })}
      fill="solid"
      label="Email"
      labelPlacement="floating"
      helperText="Enter a valid email"
      errorText="Invalid email"
      onIonInput={(event) => validate(event)}
      onIonBlur={() => markTouched()}
    ></IonTextarea>
  );
}
export default Example;

Vue

<template>
  <ion-textarea
    ref="input"
    fill="solid"
    label="Email"
    label-placement="floating"
    helper-text="Enter a valid email"
    error-text="Invalid email"
    @ionInput="validate"
    @ionBlur="markTouched"
  ></ion-textarea>
</template>

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

  const input = ref();

  const validateEmail = (email) => {
    return email.match(
      /^(?=.{1,254}$)(?=.{1,64}@)[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
    );
  };

  const validate = (event) => {
    const value = event.target.value;

    input.value.$el.classList.remove('ion-valid');
    input.value.$el.classList.remove('ion-invalid');

    if (value === '') return;

    validateEmail(value) ? input.value.$el.classList.add('ion-valid') : input.value.$el.classList.add('ion-invalid');
  };

  const markTouched = () => {
    input.value.$el.classList.add('ion-touched');
  };
</script>

Textarea Counter

Textarea counter는 textarea 아래에 표시되어 textarea가 허용할 총 문자 수 중 현재 입력된 문자 수를 알려 주는 텍스트예요. counter를 추가하면 기본 동작은 표시되는 값을 inputLength / maxLength 형식으로 포맷하는 거예요. 이 동작은 counterFormatter 프로퍼티에 포맷터 함수를 전달해 커스터마이즈할 수 있어요.

JavaScript

<ion-textarea label="Default counter" label-placement="floating" counter="true" maxlength="20"></ion-textarea>

<ion-textarea
  id="custom-textarea"
  label="Custom Counter Format"
  label-placement="floating"
  counter="true"
  maxlength="20"
></ion-textarea>

<script>
  const customTextarea = document.querySelector('#custom-textarea');
  customTextarea.counterFormatter = (inputLength, maxLength) => `${maxLength - inputLength} characters remaining`;
</script>

Angular

src/app/example.component.html

<ion-textarea label="Default counter" labelPlacement="floating" [counter]="true" maxlength="20"></ion-textarea>

<ion-textarea
  label="Custom Counter Format"
  labelPlacement="floating"
  [counter]="true"
  maxlength="20"
  [counterFormatter]="customCounterFormatter"
></ion-textarea>

src/app/example.component.ts

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

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonTextarea],
})
export class ExampleComponent {
  customCounterFormatter(inputLength: number, maxLength: number) {
    return `${maxLength - inputLength} characters remaining`;
  }
}

React

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

function Example() {
  return (
    <>
      <IonTextarea label="Default counter" labelPlacement="floating" counter={true} maxlength={20}></IonTextarea>

      <IonTextarea
        label="Custom Counter Format"
        labelPlacement="floating"
        counter={true}
        maxlength={20}
        counterFormatter={(inputLength, maxLength) => `${maxLength - inputLength} characters remaining`}
      ></IonTextarea>
    </>
  );
}
export default Example;

Vue

<template>
  <ion-textarea label="Default counter" label-placement="floating" :counter="true" maxlength="20"></ion-textarea>

  <ion-textarea
    label="Custom Counter Format"
    label-placement="floating"
    :counter="true"
    maxlength="20"
    :counter-formatter="customFormatter"
  ></ion-textarea>
</template>

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

  const customFormatter = (inputLength, maxLength) => {
    return `${maxLength - inputLength} characters remaining`;
  };
</script>

Autogrow

autoGrow 프로퍼티를 true로 설정하면 textarea가 내용에 따라 커지고 작아져요.

JavaScript

<ion-item>
  <ion-textarea
    placeholder="Type something here"
    auto-grow="true"
    value="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris tellus sem, auctor accumsan egestas sed, venenatis at ex. Nam consequat ex odio, suscipit rhoncus orci dictum eget. Aenean sit amet ligula varius felis facilisis lacinia nec volutpat nulla. Duis ullamcorper sit amet turpis sed blandit. Integer pretium massa eu faucibus interdum."
  >
  </ion-textarea>
</ion-item>

Angular

src/app/example.component.html

<ion-item>
  <ion-textarea
    placeholder="Type something here"
    [autoGrow]="true"
    value="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris tellus sem, auctor accumsan egestas sed, venenatis at ex. Nam consequat ex odio, suscipit rhoncus orci dictum eget. Aenean sit amet ligula varius felis facilisis lacinia nec volutpat nulla. Duis ullamcorper sit amet turpis sed blandit. Integer pretium massa eu faucibus interdum."
  >
  </ion-textarea>
</ion-item>

src/app/example.component.ts

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

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

React

import React from 'react';
import { IonItem, IonTextarea } from '@ionic/react';
function Example() {
  return (
    <IonItem>
      <IonTextarea
        placeholder="Type something here"
        autoGrow={true}
        value="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris tellus sem, auctor accumsan egestas sed, venenatis at ex. Nam consequat ex odio, suscipit rhoncus orci dictum eget. Aenean sit amet ligula varius felis facilisis lacinia nec volutpat nulla. Duis ullamcorper sit amet turpis sed blandit. Integer pretium massa eu faucibus interdum."
      ></IonTextarea>
    </IonItem>
  );
}
export default Example;

Vue

<template>
  <ion-item>
    <ion-textarea
      placeholder="Type something here"
      :auto-grow="true"
      value="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris tellus sem, auctor accumsan egestas sed, venenatis at ex. Nam consequat ex odio, suscipit rhoncus orci dictum eget. Aenean sit amet ligula varius felis facilisis lacinia nec volutpat nulla. Duis ullamcorper sit amet turpis sed blandit. Integer pretium massa eu faucibus interdum."
    >
    </ion-textarea>
  </ion-item>
</template>

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

Clear on Edit

clearOnEdit 프로퍼티를 true로 설정하면 textarea가 blur된 후 다시 입력할 때 값이 비워져요.

JavaScript

<ion-textarea
  placeholder="Enter text, leave the textarea, come back, and type to clear"
  clear-on-edit="true"
></ion-textarea>

Angular

src/app/example.component.html

<ion-textarea
  placeholder="Enter text, leave the textarea, come back, and type to clear"
  [clearOnEdit]="true"
></ion-textarea>

src/app/example.component.ts

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

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

React

import React from 'react';
import { IonTextarea } from '@ionic/react';
function Example() {
  return (
    <IonTextarea
      placeholder="Enter text, leave the textarea, come back, and type to clear"
      clearOnEdit={true}
    ></IonTextarea>
  );
}
export default Example;

Vue

<template>
  <ion-textarea
    placeholder="Enter text, leave the textarea, come back, and type to clear"
    :clear-on-edit="true"
  ></ion-textarea>
</template>

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

Start and End Slots (experimental)

start와 end 슬롯을 사용해 textarea 양쪽에 아이콘, 버튼, 또는 접두사/접미사 텍스트를 배치할 수 있어요.

이 기능은 Web Component slots의 시뮬레이션 버전에 의존하기 때문에 실험적인 것으로 간주돼요. 그 결과 시뮬레이션된 동작이 네이티브 슬롯 동작과 정확히 일치하지 않을 수 있어요.

Note

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

JavaScript

index.html

<ion-list>
  <ion-item>
    <ion-textarea label-placement="stacked" label="Comments" placeholder="Enter your comments">
      <ion-icon slot="start" name="lock-closed" aria-hidden="true"></ion-icon>
      <ion-button fill="clear" slot="end" aria-label="Show/hide">
        <ion-icon slot="icon-only" name="eye" aria-hidden="true"></ion-icon>
      </ion-button>
    </ion-textarea>
  </ion-item>
</ion-list>

index.ts

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

import { addIcons } from 'ionicons';
import { eye, lockClosed } 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, 'lock-closed': lockClosed });
 */
addIcons({ eye, lockClosed });

defineCustomElements();

Angular

src/app/example.component.html

<ion-list>
  <ion-item>
    <ion-textarea labelPlacement="stacked" label="Comments" placeholder="Enter your comments">
      <ion-icon slot="start" name="lock-closed" aria-hidden="true"></ion-icon>
      <ion-button fill="clear" slot="end" aria-label="Show/hide">
        <ion-icon slot="icon-only" name="eye" aria-hidden="true"></ion-icon>
      </ion-button>
    </ion-textarea>
  </ion-item>
</ion-list>

src/app/example.component.ts

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

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

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonButton, IonIcon, IonItem, IonList, IonTextarea],
})
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, lockClosed });
  }
}

React

import React from 'react';
import { IonButton, IonIcon, IonItem, IonList, IonTextarea } from '@ionic/react';
import { eye, lockClosed } from 'ionicons/icons';

function Example() {
  return (
    <IonList>
      <IonItem>
        <IonTextarea labelPlacement="stacked" label="Comments" placeholder="Enter your comments">
          <IonIcon slot="start" icon={lockClosed} aria-hidden="true"></IonIcon>
          <IonButton fill="clear" slot="end" aria-label="Show/hide">
            <IonIcon slot="icon-only" icon={eye} aria-hidden="true"></IonIcon>
          </IonButton>
        </IonTextarea>
      </IonItem>
    </IonList>
  );
}
export default Example;

Vue

<template>
  <ion-list>
    <ion-item>
      <ion-textarea label-placement="stacked" label="Comments" placeholder="Enter your comments">
        <ion-icon slot="start" :icon="lockClosed" aria-hidden="true"></ion-icon>
        <ion-button fill="clear" slot="end" aria-label="Show/hide">
          <ion-icon slot="icon-only" :icon="eye" aria-hidden="true"></ion-icon>
        </ion-button>
      </ion-textarea>
    </ion-item>
  </ion-list>
</template>

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

Theming

JavaScript

<ion-textarea
  aria-label="Custom textarea"
  placeholder="Type something here"
  class="custom"
  helper-text="Helper text"
  counter="true"
  maxlength="100"
></ion-textarea>

<style>
  ion-textarea.custom {
    --background: #373737;
    --color: #fff;
    --padding-end: 10px;
    --padding-start: 10px;
    --placeholder-color: #ddd;
    --placeholder-opacity: 0.8;
  }

  ion-textarea.custom.ios .textarea-bottom .helper-text,
  ion-textarea.custom.ios .textarea-bottom .counter,
  ion-textarea.custom.md .textarea-bottom .helper-text,
  ion-textarea.custom.md .textarea-bottom .counter {
    color: var(--ion-color-primary);
  }
</style>

Angular

src/app/example.component.html

<ion-textarea
  aria-label="Custom textarea"
  placeholder="Type something here"
  class="custom"
  helperText="Helper text"
  [counter]="true"
  [maxlength]="100"
></ion-textarea>

src/app/example.component.css

ion-textarea.custom {
  --background: #373737;
  --color: #fff;
  --padding-end: 10px;
  --padding-start: 10px;
  --placeholder-color: #ddd;
  --placeholder-opacity: 0.8;
}

src/app/example.component.ts

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

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

src/global.css

/**
 * Since we are styling elements inside of ion-textarea
 * we need to move this CSS to a global stylesheet. Otherwise,
 * Angular components with encapsulation enabled will add
 * scoped style attributes to these selectors.
 */
ion-textarea.custom.ios .textarea-bottom .helper-text,
ion-textarea.custom.ios .textarea-bottom .counter,
ion-textarea.custom.md .textarea-bottom .helper-text,
ion-textarea.custom.md .textarea-bottom .counter {
  color: var(--ion-color-primary);
}

React

src/main.css

ion-textarea.custom {
  --background: #373737;
  --color: #fff;
  --padding-end: 10px;
  --padding-start: 10px;
  --placeholder-color: #ddd;
  --placeholder-opacity: 0.8;
}

ion-textarea.custom.ios .textarea-bottom .helper-text,
ion-textarea.custom.ios .textarea-bottom .counter,
ion-textarea.custom.md .textarea-bottom .helper-text,
ion-textarea.custom.md .textarea-bottom .counter {
  color: var(--ion-color-primary);
}

src/main.tsx

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

import './main.css';

function Example() {
  return (
    <IonTextarea
      aria-label="Custom textarea"
      placeholder="Type something here"
      class="custom"
      helperText="Helper text"
      counter={true}
      maxlength={100}
    ></IonTextarea>
  );
}
export default Example;

Vue

<style>
  ion-textarea.custom {
    --background: #373737;
    --color: #fff;
    --padding-end: 10px;
    --padding-start: 10px;
    --placeholder-color: #ddd;
    --placeholder-opacity: 0.8;
  }

  ion-textarea.custom.ios .textarea-bottom .helper-text,
  ion-textarea.custom.ios .textarea-bottom .counter,
  ion-textarea.custom.md .textarea-bottom .helper-text,
  ion-textarea.custom.md .textarea-bottom .counter {
    color: var(--ion-color-primary);
  }
</style>

<template>
  <ion-textarea
    aria-label="Custom textarea"
    placeholder="Type something here"
    class="custom"
    helper-text="Helper text"
    :counter="true"
    :maxlength="100"
  ></ion-textarea>
</template>

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

Interfaces

TextareaChangeEventDetail

interface TextareaChangeEventDetail {
  value?: string | null;
}

TextareaCustomEvent

필수는 아니지만 이 인터페이스는 이 컴포넌트에서 발생하는 Ionic 이벤트에 더 강한 타입을 부여하기 위해 CustomEvent 인터페이스 대신 사용할 수 있어요.

interface TextareaCustomEvent extends CustomEvent {
  detail: TextareaChangeEventDetail;
  target: HTMLIonTextareaElement;
}

Properties

autoGrow

Description: true로 설정하면 textarea 컨테이너가 textarea의 내용에 따라 커지고 작아져요.

Attribute: auto-grow

Type: boolean

Default: false

autocapitalize

Description: 사용자가 입력/수정할 때 텍스트 값을 자동으로 대문자화할지 여부와 방법을 나타내요. 사용 가능한 옵션: "off", "none", "on", "sentences", "words", "characters".

Attribute: autocapitalize

Type: string

Default: 'none'

autofocus

Description: 네이티브 input 요소에 autofocus attribute를 설정해요. 이 설정만으로는 페이지 로드 시 요소가 포커스되기에 충분하지 않을 수 있어요. 자세한 내용은 managing focus를 참고해 주세요.

Attribute: autofocus

Type: boolean

Default: false

clearOnEdit

Description: true로 설정하면 편집 중 포커스된 후에 값이 비워져요.

Attribute: clear-on-edit

Type: boolean

Default: false

color

Description: 앱의 색상 팔레트에서 사용할 색상이에요. 기본 옵션은 "primary", "secondary", "tertiary", "success", "warning", "danger", "light", "medium", "dark"예요. 색상에 대한 자세한 내용은 theming 문서를 참고해 주세요.

Attribute: color

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

Default: undefined

cols

Description: 평균 문자 너비로 나타낸 텍스트 제어 요소의 표시 너비예요. 지정한다면 양의 정수여야 해요.

Attribute: cols

Type: number | undefined

Default: undefined

counter

Description: true로 설정하면 문자 카운터가 사용된 문자 수와 총 문자 제한의 비율을 표시해요. 카운터가 올바르게 계산되려면 maxlength 프로퍼티도 설정해야 해요.

Attribute: counter

Type: boolean

Default: false

counterFormatter

Description: counter 텍스트를 포맷하는 데 사용되는 콜백이에요. 기본적으로 counter 텍스트는 "itemLength / maxLength"로 설정돼요. 콜백 안에서 this에 접근해야 한다면 https://ionicframework.com/docs/troubleshooting/runtime#accessing-this를 참고해 주세요.

Attribute: undefined

Type: ((inputLength: number, maxLength: number) => string) | undefined

Default: undefined

debounce

Description: 각 키 입력 후 ionInput 이벤트를 발생시키기까지 기다릴 시간(밀리초)을 설정해요.

Attribute: debounce

Type: number | undefined

Default: undefined

disabled

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

Attribute: disabled

Type: boolean

Default: false

enterkeyhint

Description: 표시할 enter 키에 대한 힌트를 브라우저에 제공해요. 가능한 값: "enter", "done", "go", "next", "previous", "search", "send".

Attribute: enterkeyhint

Type: "done" | "enter" | "go" | "next" | "previous" | "search" | "send" | undefined

Default: undefined

errorText

Description: 오류가 감지되었을 때 textarea 아래에 표시되는 텍스트예요.

Attribute: error-text

Type: string | undefined

Default: undefined

fill

Description: item의 채움(fill)이에요. "solid"이면 item에 배경이 생기고, "outline"이면 테두리가 있는 투명한 상태가 돼요. md mode에서만 사용할 수 있어요.

Attribute: fill

Type: "outline" | "solid" | undefined

Default: undefined

helperText

Description: 오류가 감지되지 않았을 때 textarea 아래에 표시되는 텍스트예요.

Attribute: helper-text

Type: string | undefined

Default: undefined

inputmode

Description: 표시할 키보드에 대한 힌트를 브라우저에 제공해요. 가능한 값: "none", "text", "tel", "url", "email", "numeric", "decimal", "search".

Attribute: inputmode

Type: "decimal" | "email" | "none" | "numeric" | "search" | "tel" | "text" | "url" | undefined

Default: undefined

label

Description: textarea와 연결된 눈에 보이는 라벨이에요. 일반 텍스트 라벨을 렌더링해야 한다면 이것을 사용해요. label 프로퍼티와 label 슬롯을 모두 사용하면 label 프로퍼티가 우선해요.

Attribute: label

Type: string | undefined

Default: undefined

labelPlacement

Description: textarea 기준으로 라벨을 어디에 배치할지 결정해요. "start": 라벨이 LTR에서는 textarea 왼쪽, RTL에서는 오른쪽에 나타나요. "end": 라벨이 LTR에서는 textarea 오른쪽, RTL에서는 왼쪽에 나타나요. "floating": textarea가 포커스되거나 값이 있으면 라벨이 더 작게 textarea 위에 나타나요. 그 외에는 textarea 위에 겹쳐 나타나요. "stacked": textarea가 blur되거나 값이 없어도 라벨이 더 작게 textarea 위에 항상 나타나요. "fixed": 라벨이 "start"와 같은 동작을 하지만 고정된 너비를 가져요. 긴 텍스트는 줄임표("...")로 잘려요.

Attribute: label-placement

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

Default: 'start'

maxlength

Description: 사용자가 입력할 수 있는 최대 문자 수를 지정하는 속성이에요.

Attribute: maxlength

Type: number | undefined

Default: undefined

minlength

Description: 사용자가 입력할 수 있는 최소 문자 수를 지정하는 속성이에요.

Attribute: minlength

Type: number | undefined

Default: undefined

mode

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

Attribute: mode

Type: "ios" | "md"

Default: undefined

name

Description: 폼 데이터와 함께 제출되는 제어 요소의 이름이에요.

Attribute: name

Type: string

Default: this.inputId

placeholder

Description: 입력에 값이 있기 전에 표시되는 안내 텍스트예요.

Attribute: placeholder

Type: string | undefined

Default: undefined

readonly

Description: true로 설정하면 사용자가 값을 수정할 수 없어요.

Attribute: readonly

Type: boolean

Default: false

required

Description: true로 설정하면 사용자가 폼을 제출하기 전에 값을 입력해야 해요.

Attribute: required

Type: boolean

Default: false

rows

Description: 제어 요소에 표시되는 텍스트 줄 수예요.

Attribute: rows

Type: number | undefined

Default: undefined

shape

Description: textarea의 모양이에요. "round"이면 테두리의 둥근 정도가 증가해요.

Attribute: shape

Type: "round" | undefined

Default: undefined

spellcheck

Description: true로 설정하면 요소의 철자와 문법이 검사돼요.

Attribute: spellcheck

Type: boolean

Default: false

value

Description: textarea의 값이에요.

Attribute: value

Type: null | string | undefined

Default: ''

wrap

Description: 제어 요소가 텍스트를 어떻게 줄 바꿈하는지 나타내요.

Attribute: wrap

Type: "hard" | "off" | "soft" | undefined

Default: undefined

Events

Name Description Bubbles
ionBlur 입력이 포커스를 잃을 때 발생해요. true
ionChange ionChange 이벤트는 사용자가 textarea의 값을 수정할 때 발생해요. ionInput 이벤트와 달리 ionChange 이벤트는 값이 수정된 후 요소가 포커스를 잃을 때 발생해요. 이 이벤트는 value 프로퍼티를 프로그래밍 방식으로 설정할 때는 발생하지 않아요. true
ionFocus 입력에 포커스가 있을 때 발생해요. true
ionInput ionInput 이벤트는 사용자가 textarea의 값을 수정할 때마다 발생해요. ionChange 이벤트와 달리 ionInput 이벤트는 textarea 값의 각 변경마다 발생해요. 이는 보통 사용자가 입력할 때 키 입력마다 발생해요. clearOnEdit가 활성화되면 사용자가 keydown 이벤트로 textarea를 지울 때 ionInput 이벤트가 발생해요. true

Methods

getInputElement

Description: 내부에서 사용되는 네이티브 <textarea> 요소를 반환해요.

Signature: getInputElement() => Promise<HTMLTextAreaElement>

setFocus

Description: ion-textarea의 네이티브 textarea에 포커스를 설정해요. 전역 textarea.focus() 대신 이 메서드를 사용해 주세요. 자세한 내용은 managing focus를 참고해 주세요.

Signature: setFocus() => Promise<void>

CSS Shadow Parts

이 컴포넌트에는 사용할 수 있는 CSS shadow part가 없어요.

CSS Custom Properties

iOS

Name Description
--background textarea의 배경색
--border-color helper text, error text, counter를 사용할 때 textarea 아래 테두리의 색상
--border-radius textarea 테두리의 둥근 정도
--border-style helper text, error text, counter를 사용할 때 textarea 아래 테두리의 스타일
--border-width helper text, error text, counter를 사용할 때 textarea 아래 테두리의 두께
--color 텍스트의 색상
--highlight-color-focused 포커스됐을 때 textarea 하이라이트의 색상
--highlight-color-invalid 유효하지 않을 때 textarea 하이라이트의 색상
--highlight-color-valid 유효할 때 textarea 하이라이트의 색상
--highlight-height textarea 하이라이트의 높이. md mode에만 적용돼요.
--padding-bottom textarea의 아래쪽 안쪽 여백
--padding-end 왼쪽에서 오른쪽 방향이면 오른쪽, 오른쪽에서 왼쪽 방향이면 왼쪽의 안쪽 여백
--padding-start 왼쪽에서 오른쪽 방향이면 왼쪽, 오른쪽에서 왼쪽 방향이면 오른쪽의 안쪽 여백
--padding-top textarea의 위쪽 안쪽 여백
--placeholder-color placeholder 텍스트의 색상
--placeholder-font-style placeholder 텍스트의 스타일
--placeholder-font-weight placeholder 텍스트의 두께
--placeholder-opacity placeholder 텍스트의 불투명도

MD

Name Description
--background textarea의 배경색
--border-color helper text, error text, counter를 사용할 때 textarea 아래 테두리의 색상
--border-radius textarea 테두리의 둥근 정도
--border-style helper text, error text, counter를 사용할 때 textarea 아래 테두리의 스타일
--border-width helper text, error text, counter를 사용할 때 textarea 아래 테두리의 두께
--color 텍스트의 색상
--highlight-color-focused 포커스됐을 때 textarea 하이라이트의 색상
--highlight-color-invalid 유효하지 않을 때 textarea 하이라이트의 색상
--highlight-color-valid 유효할 때 textarea 하이라이트의 색상
--highlight-height textarea 하이라이트의 높이. md mode에만 적용돼요.
--padding-bottom textarea의 아래쪽 안쪽 여백
--padding-end 왼쪽에서 오른쪽 방향이면 오른쪽, 오른쪽에서 왼쪽 방향이면 왼쪽의 안쪽 여백
--padding-start 왼쪽에서 오른쪽 방향이면 왼쪽, 오른쪽에서 왼쪽 방향이면 오른쪽의 안쪽 여백
--padding-top textarea의 위쪽 안쪽 여백
--placeholder-color placeholder 텍스트의 색상
--placeholder-font-style placeholder 텍스트의 스타일
--placeholder-font-weight placeholder 텍스트의 두께
--placeholder-opacity placeholder 텍스트의 불투명도

Slots

Name Description
end textarea의 끝(오른쪽) 가장자리에 표시할 콘텐츠. (실험적)
label textarea와 연결할 라벨 텍스트. labelPlacement 프로퍼티로 라벨이 textarea 기준으로 어디에 배치될지 제어해요. 커스텀 HTML로 라벨을 렌더링해야 한다면 이것을 사용해요. (실험적)
start textarea의 시작(왼쪽) 가장자리에 표시할 콘텐츠. (실험적)

더 알아보기 (Learn more)

textarea는 라벨 배치, helper/error text, 카운터, 자동 크기 조절 등 다양한 기능을 지원해요. 폼 검증과 결합하면 완성도 높은 입력 화면을 만들 수 있어요. label과 관련된 더 자세한 설명은 label 문서를 참고해 주세요.