Angular 툴팁 지시문 개요

    The igxTooltip and the igxTooltipTarget directives provide us with the ability to create a fully customizable tooltip and attach it to any element on our page. While most tooltips have a limited number of available positions, with the igxTooltipTarget directive we can specify any position we want on the page while keeping it in relation to the target (anchor) and provide various other overlay settings like scroll strategies and custom animations!

    Angular Tooltip Example

    Getting Started with Ignite UI for Angular Tooltip

    Ignite UI for Angular Tooltip 지시문을 시작하려면 먼저 Ignite UI for Angular 설치해야 합니다. 기존 Angular 애플리케이션에서 다음 명령을 입력합니다.

    ng add igniteui-angular
    

    Ignite UI for Angular에 대한 전체 소개는 시작 항목을 참조하십시오.

    The next step is to import the IgxTooltipModule in your app.module.ts file.

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

    Alternatively, as of 16.0.0 you can import the IgxTooltipDirective as a standalone dependency, or use the IGX_TOOLTIP_DIRECTIVES token to import the component and all of its supporting components and directives.

    // home.component.ts
    
    import { IGX_TOOLTIP_DIRECTIVES, IgxAvatarComponent } from 'igniteui-angular';
    // import { IGX_TOOLTIP_DIRECTIVES, IgxAvatarComponent } from '@infragistics/igniteui-angular'; for licensed package
    
    @Component({
      selector: 'app-home',
      template: `
        <igx-avatar
          class="avatar"
          #target="tooltipTarget"
          [igxTooltipTarget]="tooltipRef"
          src="assets/images/avatar/10.jpg"
          size="medium"
          shape="circle"
        >
        </igx-avatar>
    
        <div #tooltipRef="tooltip" igxTooltip>Her name is Madelyn James</div>
      `,
      styleUrls: ['home.component.scss'],
      standalone: true,
      imports: [IGX_TOOLTIP_DIRECTIVES, IgxAvatarComponent],
      /* or imports: [IgxTooltipDirective, IgxTooltipTargetDirective, IgxAvatarComponent] */
    })
    export class HomeComponent {}
    

    Now that you have the Ignite UI for Angular Tooltip module or directives imported, you can start using the igxTooltip directive.

    Using the Angular Tooltip

    Let's say we want to create a simple text tooltip like the one above. In our case, we're using our awesome IgxAvatar as the element, so we start by importing the IgxAvatarModule first.

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

    Tooltip target

    The avatar will be our target and all we have to do is set the igxTooltipTarget directive on it, which basically marks our element as one that has a tooltip.

    <!--simpleTooltip.component.html-->
    
    <igx-avatar
      class="avatar"
      #target="tooltipTarget"
      igxTooltipTarget
      src="assets/images/avatar/10.jpg"
      size="medium"
      shape="circle">
    </igx-avatar>
    

    툴팁

    Now let's create the tooltip element itself! Since we want a simple text tooltip, we will define an ordinary div element with text inside and set the igxTooltip directive on it, which marks it as a tooltip.

    <!--simpleTooltip.component.html-->
    
    <div #tooltipRef="tooltip" igxTooltip>Her name is Madelyn James</div>
    

    Attach tooltip to target

    Now that we have both our target and tooltip defined, all that's left for us to do is assign the tooltip's reference to the igxTooltipTarget selector of the target.

    <!--simpleTooltip.component.html-->
    
    <igx-avatar
      class="avatar"
      #target="tooltipTarget"
      [igxTooltipTarget]="tooltipRef"
      src="assets/images/avatar/10.jpg"
      size="medium"
      shape="circle">
    </igx-avatar>
    
    <div #tooltipRef="tooltip" igxTooltip>Her name is Madelyn James</div>
    

    모든 것이 잘 진행되었다면 도구 설명 데모 섹션에 표시된 샘플을 볼 수 있습니다.

    Rich tooltip

    The igxTooltip content can be more than just simple text. Since the tooltip itself is a regular element in the markup, you can enhance its content by adding any elements you need and styling them accordingly.

    Let's expand on the use of the igxTooltip and use it to provide more details for a specific location on a map! We'll use a simple div to represent our map, the IgxAvatar for a logo in our tooltip and the IgxIcon for the location icon on our map. For this purpose, we will get their respective modules.

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

    또한 애플리케이션에는 다음 스타일을 사용합니다.

    /* richTooltip.component.css */
    
    .location:hover {
      cursor: pointer;
    }
    
    .map {
      overflow: hidden;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 200px;
      height: 252px;
      background-image: url(assets/images/card/media/infragisticsMap.png);
      border: 1px solid #d4d4d4;
    }
    
    .locationTooltip {
      width: 310px;
      background-color: var(--igx-grays-700);
      padding: 3px;
      font-size: 13px;
    }
    
    .locationTooltipContent {
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .logo {
      margin-right: 10px;
      min-width: 25px;
      width: 45px;
      height: 45px;
    }
    

    지도를 만드는 것부터 시작해 보겠습니다. 배경에 지도가 포함된 이미지가 있는 간단한 div가 필요합니다. 또한 우리 위치의 위치를 나타내는 아이콘을 추가하겠습니다! 이 위치에 대한 자세한 정보를 제공하고 싶기 때문에 아이콘이 당연히 툴팁 대상이 됩니다.

    <!--richTooltip.component.html-->
    
    <div class="map">
      <igx-icon
        class="location"
        [style.color]="'blue'"
        fontSet="material"
        [igxTooltipTarget]="locationTooltip"
        >location_on</igx-icon>
      ...
    </div>
    

    이제 툴팁을 살펴보겠습니다! 콘텐츠의 경우 일부 텍스트 정보 요소와 아바타로 채워지는 컨테이너를 만듭니다. 그런 다음 툴팁을 대상에 첨부하고 멋진 CSS 스타일을 포함하겠습니다!

    <!--richTooltip.component.html-->
    
    <div class="wrapper">
      <div class="map">
        <igx-icon
          class="location"
          [style.color]="'blue'"
          fontSet="material"
          [igxTooltipTarget]="locationTooltip"
          >location_on</igx-icon>
    
        <div class="locationTooltip" #locationTooltip="tooltip" igxTooltip>
          <div class="locationTooltipContent">
            <igx-avatar
              class="logo"
              src="assets/images/card/avatars/igLogo.png"
              size="medium"
              shape="square">
            </igx-avatar>
            <div>
              <div>Infragistics Inc. HQ</div>
              <div>2 Commerce Dr, Cranbury, NJ 08512, USA</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    

    모든 것이 순조롭게 진행되었다면 위치와 툴팁은 다음과 같습니다:

    Advanced Example

    The tooltip integrates seamlessly with other components, allowing you to create advanced tooltips that contain components within them. In the following example, you can see how we create descriptive tooltips by using the IgxList, IgxAvatar, IgxIcon, IgxBadge, IgxButton, IgxCard and IgxCategoryChart components.

    Show/Hide delay settings

    What if we want to control the amount of time that should pass before showing and hiding the tooltip? For this purpose we can use the showDelay and the hideDelay properties of the igxTooltipTarget directive. Both properties are of type number and take time in milliseconds.

    Note

    The built-in UI interaction behavior of the IgxTooltipTargetDirective works by taking showDelay and hideDelay property values into account. Showing and hiding the tooltip through the API or the API of the IgxTooltipDirective does NOT take the showDelay and hideDelay property values into account. If necessary, such logic would have to be implemented manually according to the application's specifics.

    Overlay configuration

    Both the igxTooltip and igxTooltipTarget directives use the IgxOverlayService to open and close the respective tooltip element.

    The igxTooltipTarget directive exposes a positionSettings property, which can be used to customize the animations of our tooltip, its position in the UI and a lot more! If this property is not set, then default position settings will be used.

    To further customize the tooltip, use the overlaySettings property (inherited from the igxToggleAction).

    <igx-icon [igxTooltipTarget]="tooltipRef" [positionSettings]="positionSettings" [overlaySettings]="overlaySettings">
      info
    </igx-icon>
    
    <div #tooltipRef="tooltip" igxTooltip>Her name is Madelyn James</div>
    
    public positionSettings: PositionSettings = {
      horizontalDirection: HorizontalAlignment.Left,
      horizontalStartPoint: HorizontalAlignment.Left,
      verticalDirection: VerticalAlignment.Top,
      verticalStartPoint: VerticalAlignment.Bottom,
      openAnimation: useAnimation(slideInTop, { params: { duration: '2000ms' } }),
      closeAnimation: useAnimation(slideOutBottom, { params: { duration: '2000ms'} }),
      offset: 10
    }
    
    public overlaySettings: OverlaySettings = {
      closeOnEscape: false,
    };
    
    Note

    Any property that is set through the positionSettings or overlaySettings will override the same property from the default settings and will have a direct impact on the tooltip.

    Additional Properties

    Apart from the properties we've already covered, the igxTooltipTarget offers a variety of additional properties that allow you to further configure the tooltip's behavior and appearance.

    You can make the tooltip "sticky" using the sticky property, which adds a close button and keeps the tooltip visible until the user closes it manually - either by clicking the close button or pressing the Esc key. This behavior overrides the default hover behavior, preventing the tooltip from disappearing when the user stops hovering over the target element.

    <igx-icon [igxTooltipTarget]="tooltipRef" [sticky]="true">
      info
    </igx-icon>
    
    <div #tooltipRef="tooltip" igxTooltip>Her name is Madelyn James</div>
    

    To customize the default close button, use the closeButtonTemplate property.

    
    <igx-icon [igxTooltipTarget]="tooltipRef" [sticky]="true" [closeButtonTemplate]="customTemplate">
      info
    </igx-icon>
    
    <ng-template #customTemplate>
      <igx-icon>cancel</igx-icon>
    </ng-template>
    
    <div #tooltipRef="tooltip" igxTooltip>Her name is Madelyn James</div>
    
    Note

    Any custom content added via the closeButtonTemplate is rendered only when the tooltip is in sticky mode.

    Additionally, you can add an arrow indicator to the tooltip by using the hasArrow property.

    <igx-icon [igxTooltipTarget]="tooltipRef" [hasArrow]="true">
      info
    </igx-icon>
    
    <div #tooltipRef="tooltip" igxTooltip>Her name is Madelyn James</div>
    

    The arrow element is positioned based on the provided position settings. If the directions and starting points do not correspond to any of the predefined position values, the arrow is positioned in the top middle side of the tooltip (default tooltip position bottom).

    미리 정의된 위치 값

    위치 수평 방향 수평 시작점 수직 방향 수직 시작점
    맨 위 수평정렬.중심 수평정렬.중심 VerticalAlignment.Top VerticalAlignment.Top
    최고 시작 수평 정렬.오른쪽 수평정렬.왼쪽 VerticalAlignment.Top VerticalAlignment.Top
    최고급 수평정렬.왼쪽 수평 정렬.오른쪽 VerticalAlignment.Top VerticalAlignment.Top
    맨 아래 수평정렬.중심 수평정렬.중심 수직 정렬.하단 수직 정렬.하단
    하단 시작 수평 정렬.오른쪽 수평정렬.왼쪽 수직 정렬.하단 수직 정렬.하단
    최하위 수평정렬.왼쪽 수평 정렬.오른쪽 수직 정렬.하단 수직 정렬.하단
    오른쪽 수평 정렬.오른쪽 수평 정렬.오른쪽 수직정렬.중간 수직정렬.중간
    오른쪽 시작 수평 정렬.오른쪽 수평 정렬.오른쪽 수직 정렬.하단 VerticalAlignment.Top
    오른쪽 끝 수평 정렬.오른쪽 수평 정렬.오른쪽 VerticalAlignment.Top 수직 정렬.하단
    왼쪽 수평정렬.왼쪽 수평정렬.왼쪽 수직정렬.중간 수직정렬.중간
    왼쪽 시작 수평정렬.왼쪽 수평정렬.왼쪽 수직 정렬.하단 VerticalAlignment.Top
    왼쪽 끝 수평정렬.왼쪽 수평정렬.왼쪽 VerticalAlignment.Top 수직 정렬.하단

    다음 예에서는 모든 위치 옵션과 화살표 위치 지정 동작의 데모를 볼 수 있습니다.

    화살표 위치 사용자 지정

    To customize the arrow's position, you can override the positionArrow(arrow: HTMLElement, arrowFit: ArrowFit) method.

    예를 들어:

    export class CustomStrategy extends TooltipPositioningStrategy {
      constructor(settings?: PositionSettings) {
        super(settings);
      }
    
      public override positionArrow(arrow: HTMLElement, arrowFit: ArrowFit): void {
        Object.assign(arrow.style, {
          left: '-0.25rem',
          transform: 'rotate(-45deg)',
          [arrowFit.direction]: '-0.25rem',
        });
      }
    }
    
    public overlaySettings: OverlaySettings = {
      positionStrategy: new CustomStrategy({
        horizontalDirection: HorizontalAlignment.Right,
        horizontalStartPoint: HorizontalAlignment.Right,
        verticalDirection: VerticalAlignment.Bottom,
        verticalStartPoint: VerticalAlignment.Bottom,
      })
    };
    
    <igx-icon [igxTooltipTarget]="tooltipRef" [hasArrow]="true" [overlaySettings]="overlaySettings">
      info
    </igx-icon>
    
    <div #tooltipRef="tooltip" igxTooltip>Her name is Madelyn James</div>
    

    스타일링

    To get started with styling the tooltip, we need to import the index file, where all the theme functions and component mixins live:

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

    Following the simplest approach, we create a new theme that extends the tooltip-theme and provide the $text-color, $background and the $border-radius parameters.

    $dark-tooltip: tooltip-theme(
      $text-color: #ecaa53,
      $background: #011627,
      $border-radius: 6px,
    );
    
    Note

    In order to style any additional components that are used as part of the tooltip's content (such as IgxButton, IgxSwitch, etc.), an additional theme should be created that is specific to the respective component and placed under the tooltip's scope only (so it does not affect the rest of the application).

    Since the tooltip uses the IgxOverlayService, in order for our custom theme to reach down the tooltip that we want to style, we will provide a specific outlet where the tooltip will be placed in the DOM when it is visible.

    <igx-avatar
      #target="tooltipTarget"
      [igxTooltipTarget]="tooltipRef"
      [igxToggleOutlet]="outlet"
    >
    </igx-avatar>
    
    <div #outlet="overlay-outlet" igxOverlayOutlet>
      <div #tooltipRef="tooltip" igxTooltip>Her name is Madelyn James</div>
    </div>
    

    마지막 단계는 애플리케이션에 구성 요소 테마를 포함하는 것입니다.

    @include css-vars($dark-tooltip);
    

    이제 스타일이 지정된 툴팁은 다음과 같아야 합니다.

    Demo

    Styling with Tailwind

    저희의 맞춤형 Tailwind 유틸리티 클래스를 사용해 툴팁을 스타일링할 수 있습니다. 먼저 Tailwind를 꼭 설정 하세요.

    글로벌 스타일시트에서 Tailwind 가져오기와 함께, 원하는 테마 유틸리티를 다음과 같이 적용할 수 있습니다:

    @import "tailwindcss";
    ...
    @use 'igniteui-theming/tailwind/utilities/material.css';
    

    The utility file includes both light and dark theme variants.

    • Use light-* classes for the light theme.
    • Use dark-* classes for the dark theme.
    • Append the component name after the prefix, e.g., light-tooltip, dark-tooltip.

    Once applied, these classes enable dynamic theme calculations. You can then override the generated CSS variables using arbitrary properties. After the colon, provide any valid CSS color format (HEX, CSS variable, RGB, etc.).

    전체 속성 목록은 IgxTooltip 테마에서 확인할 수 있습니다. 문법은 다음과 같습니다:

    <div
      class="!light-tooltip ![--background:#90B69F]"
      #tooltipRef="tooltip"
      igxTooltip>
      Her name is Madelyn James
    </div>
    
    Note

    The exclamation mark(!) is required to ensure the utility class takes precedence. Tailwind applies styles in layers, and without marking these styles as important, they will get overridden by the component’s default theme.

    마지막에 툴팁은 다음과 같이 보여야 합니다:

    Accessibility

    The igxTooltip is built with accessibility in mind and includes the following properties and ARIA attributes:

    • id property - autogenerated if not set by the developer.
    • role - When the tooltip is in its default behavior, role="tooltip" is applied. If the sticky property is enabled, the role changes to status.
    • aria-hidden - automatically updated depending on whether the tooltip is visible or not.

    By setting the aria-describedby attribute of the target to its respective tooltip's id, a reference will be provided to the tooltip element. This provides screen readers the information needed to read out the tooltip's contents when the end-user triggers the tooltip.

    다음 시나리오에서는 특별한 주의가 필요합니다.

    • 도구 설명 내용이 너무 복잡하여 자동으로 해석할 수 없습니다.
    • 도구 설명은 내장된 동작 대신 수동으로 구현된 동작(예: 수동으로 표시/숨기기)과 함께 사용됩니다.
    • 대상 요소에 초점을 맞출 수 없습니다.

    Notes and Limitations

    한정 설명
    화살표가 있는 사용자 지정 위치 전략 지시문은igxTooltipTargetTooltipPositionStrategy 사용하여 도구 설명 및 화살표 요소를 배치합니다. 사용자 지정positionStrategy이 사용되고hasArrowtrue 설정된 경우 사용자 지정 전략은 을 확장해야 합니다TooltipPositionStrategy. 그렇지 않으면 화살표가 표시되지 않습니다.

    API References

    이 글에서는 페이지의 요소에 대한 멋진 툴팁을 만들고, 구성하고, 스타일을 지정하는 방법을 알아보았습니다! 또한 아이콘과 아바타와 같은 추가적인 Ignite UI for Angular 구성 요소를 사용하여 애플리케이션의 디자인을 개선했습니다! 해당 API는 아래와 같습니다.

    사용된 추가 구성요소 및/또는 지시어:

    Styles:

    Additional Resources

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