Angular中怎么以Tooltip自定義指令

本文小編為大家詳細(xì)介紹“Angular中怎么以Tooltip自定義指令”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“Angular中怎么以Tooltip自定義指令”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識(shí)吧。

站在用戶的角度思考問題,與客戶深入溝通,找到青云譜網(wǎng)站設(shè)計(jì)與青云譜網(wǎng)站推廣的解決方案,憑借多年的經(jīng)驗(yàn),讓設(shè)計(jì)與互聯(lián)網(wǎng)技術(shù)結(jié)合,創(chuàng)造個(gè)性化、用戶體驗(yàn)好的作品,建站類型包括:網(wǎng)站設(shè)計(jì)制作、網(wǎng)站制作、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣、申請(qǐng)域名雅安服務(wù)器托管、企業(yè)郵箱。業(yè)務(wù)覆蓋青云譜地區(qū)。

Angular中怎么以Tooltip自定義指令

效果圖如下:

Angular中怎么以Tooltip自定義指令

目錄結(jié)構(gòu)

在上一篇文章的實(shí)現(xiàn)的代碼項(xiàng)目基礎(chǔ)上,執(zhí)行命令行:

# 進(jìn)入 directives 文件夾
$ cd directives

# 創(chuàng)建 tooltip 文件夾
$ mkdir tooltip

# 進(jìn)入 tooltip 文件夾
$ cd tooltip

# 創(chuàng)建 tooltip 組件
$ ng generate component tooltip

# 創(chuàng)建 tooltip 指令
$ ng generate directive tooltip

執(zhí)行完上面的命令行之后,你會(huì)得到 app/directive/tooltip 的文件目錄結(jié)構(gòu)如下:

tooltip
├── tooltip                                           // tooltip 組件
│    ├── user-list.component.html                     // 頁面骨架
│    ├── user-list.component.scss                     // 頁面獨(dú)有樣式
│    ├── user-list.component.spec.ts                  // 測試文件
│    └── user-list.component.ts                       // javascript 文件
├── tooltip.directive.spec.ts                         // 測試文件
└── tooltip.directive.ts                              // 指令文件

嗯,這里我將組件放在 tooltip 的同級(jí),主要是方便管理。當(dāng)然,這個(gè)因人而異,你可以放在公共組件 components 文件夾內(nèi)。

編寫 tooltip 組件

html 文件中,有:

<div class="caret"></div>
<div class="tooltip-content">{{data.content}}</div>

在樣式文件 .scss 中,有:

$black: #000000;
$white: #ffffff;
$caret-size: 6px;
$tooltip-bg: transparentize($black, 0.25); // transparentize 是 sass 的語法
$grid-gutter-width: 30px;
$body-bg-color: $white;
$app-anim-time: 200ms;
$app-anim-curve: ease-out;
$std-border-radius: 5px;
$zindex-max: 100;

// :host 偽類選擇器,給組件元素本身設(shè)置樣式
:host {
  position: fixed;
  padding: $grid-gutter-width/3 $grid-gutter-width/2;
  background-color: $tooltip-bg;
  color: $body-bg-color;
  opacity: 0;
  transition: all $app-anim-time $app-anim-curve;
  text-align: center;
  border-radius: $std-border-radius;
  z-index: $zindex-max;
}

.caret { // 脫字符
  width: 0;
  height: 0;
  border-left: 6px solid transparent;
  border-right: 6px solid transparent;
  border-bottom: 6px solid $tooltip-bg;
  position: absolute;
  top: -$caret-size;
  left: 50%;
  margin-left: -$caret-size/2;
  border-bottom-color: $tooltip-bg;
}

嗯~,css 是一個(gè)神奇的東西,之后會(huì)安排一篇文章來講解下 sass 相關(guān)的內(nèi)容...

然后,在 javascript 文件 tooltip.component.ts 內(nèi)容如下:

import { 
  Component, 
  ElementRef, // 元素指向
  HostBinding, 
  OnDestroy, 
  OnInit 
} from '@angular/core';

@Component({
  selector: 'app-tooltip', // 標(biāo)識(shí)符,表明我這個(gè)組件叫做啥,這里是 app-tooltip
  templateUrl: './tooltip.component.html', // 本組件的骨架
  styleUrls: ['./tooltip.component.scss'] // 本組件的私有樣式
})
export class TooltipComponent implements OnInit {

  public data: any; // 在 directive 上賦值
  private displayTimeOut:any;

  // 組件本身 host 綁定相關(guān)的裝飾器
  @HostBinding('style.top')  hostStyleTop!: string;
  @HostBinding('style.left') hostStyleLeft!: string;
  @HostBinding('style.opacity') hostStyleOpacity!: string;

  constructor(
    private elementRef: ElementRef
  ) { }

  ngOnInit(): void {
    this.hostStyleTop = this.data.elementPosition.bottom + 'px';

    if(this.displayTimeOut) {
      clearTimeout(this.displayTimeOut)
    }

    this.displayTimeOut = setTimeout((_: any) => {
      // 這里計(jì)算 tooltip 距離左側(cè)的距離,這里計(jì)算公式是:tooltip.left + 目標(biāo)元素的.width - (tooltip.width/2)
      this.hostStyleLeft = this.data.elementPosition.left + this.data.element.clientWidth / 2 - this.elementRef.nativeElement.clientWidth / 2 + 'px'
      this.hostStyleOpacity = '1';
      this.hostStyleTop = this.data.elementPosition.bottom + 10 + 'px'
    }, 500)
  }
  
  
  // 組件銷毀
  ngOnDestroy() {
    // 組件銷毀后,清除定時(shí)器,防止內(nèi)存泄露
    if(this.displayTimeOut) {
      clearTimeout(this.displayTimeOut)
    }
  }
}

編寫 tooltip 指令

這是本文的重點(diǎn),具體的說明,我在代碼上標(biāo)注出來~

相關(guān)的文件 tooltip.directive.ts 內(nèi)容如下:

import { 
  ApplicationRef, // 全局性調(diào)用檢測
  ComponentFactoryResolver, // 創(chuàng)建組件對(duì)象
  ComponentRef, // 組件實(shí)例的關(guān)聯(lián)和指引,指向 ComponentFactory 創(chuàng)建的元素
  Directive, ElementRef, 
  EmbeddedViewRef, // EmbeddedViewRef 繼承于 ViewRef,用于表示模板元素中定義的 UI 元素。
  HostListener, // DOM 事件監(jiān)聽
  Injector, // 依賴注入
  Input 
} from '@angular/core';

import { TooltipComponent } from './tooltip/tooltip.component';

@Directive({
  selector: '[appTooltip]'
})
export class TooltipDirective {
  @Input("appTooltip") appTooltip!: string;

  private componentRef!: ComponentRef<TooltipComponent>;

  // 獲取目標(biāo)元素的相關(guān)位置,比如 left, right, top, bottom
  get elementPosition() {
    return this.elementRef.nativeElement.getBoundingClientRect(); 
  }

  constructor(
    protected elementRef: ElementRef,
    protected appRef: ApplicationRef,
    protected componentFactoryResolver: ComponentFactoryResolver,
    protected injector: Injector
  ) { }

  // 創(chuàng)建 tooltip
  protected createTooltip() {
    this.componentRef = this.componentFactoryResolver
      .resolveComponentFactory(TooltipComponent) // 綁定 tooltip 組件
      .create(this.injector);

    this.componentRef.instance.data = { // 綁定 data 數(shù)據(jù)
      content: this.appTooltip,
      element: this.elementRef.nativeElement,
      elementPosition: this.elementPosition
    }

    this.appRef.attachView(this.componentRef.hostView); // 添加視圖
    const domElem = (this.componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement;
    document.body.appendChild(domElem);
  }
  
  // 刪除 tooltip
  protected destroyTooltip() {
    if(this.componentRef) {
      this.appRef.detachView(this.componentRef.hostView); // 移除視圖
      this.componentRef.destroy();
    }
  }
  
  // 監(jiān)聽鼠標(biāo)移入
  @HostListener('mouseover')
  OnEnter() {
    this.createTooltip();
  }
    
  // 監(jiān)聽鼠標(biāo)移出
  @HostListener('mouseout')
  OnOut() {
    this.destroyTooltip();
  }

}

到這里,已經(jīng)完成了 99% 的功能了,下面我們?cè)陧撁嫔险{(diào)用即可。

頁面上調(diào)用

我們?cè)?user-list.component.html 上添加下面的內(nèi)容:

<p style="margin-top: 100px;">
  <!-- [appTooltip]="'Hello Jimmy'" 是重點(diǎn) -->
  <span 
    [appTooltip]="'Hello Jimmy'" 
    style="margin-left: 200px; width: 160px; text-align: center; padding: 20px 0; display: inline-block; border: 1px solid #999;"
  >Jimmy</span>
</p>

TooltipDirective 這個(gè)指令我們已經(jīng)在 app.module.ts 上進(jìn)行聲明,我們直接調(diào)用即可。目前的效果如下:

Angular中怎么以Tooltip自定義指令

我們實(shí)現(xiàn)的 tooltip 是底部居中展示,也就是我們平常使用框架,比如 angular ant designtooltipbottom 屬性。對(duì)于其他屬性,讀者感興趣的話,可以進(jìn)行擴(kuò)展。

讀到這里,這篇“Angular中怎么以Tooltip自定義指令”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識(shí)點(diǎn)還需要大家自己動(dòng)手實(shí)踐使用過才能領(lǐng)會(huì),如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。

標(biāo)題名稱:Angular中怎么以Tooltip自定義指令
本文地址:http://muchs.cn/article42/jioihc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供外貿(mào)網(wǎng)站建設(shè)ChatGPT、、網(wǎng)站營銷、App開發(fā)、標(biāo)簽優(yōu)化

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站制作