[Angular] Export directive functionalities by using 'exportAs'

本文介绍了一个Angular指令示例,该指令用于创建一个可显示提示信息的组件。通过鼠标悬停在一个特定元素上触发提示信息的显示与隐藏。文章展示了如何定义Angular指令、使用输入属性定制提示内容,并提供了完整的HTML示例代码。

Directive ables to change component behaives and lookings. Directive can also export some APIs which enable behaivor changes control by outside directive iteslf.

 

For example, we have an tooltip:

It is a directive:

import { Input, Directive, ElementRef, OnInit } from '@angular/core';

@Directive({
  selector: '[tooltip]',
  exportAs: 'tooltip'
})
export class TooltipDirective implements OnInit {
  tooltipElement = document.createElement('div');
  @Input()
  set tooltip(value) {
    this.tooltipElement.innerText = value;
  }

  hide() {
    this.tooltipElement.classList.remove('tooltip--active');
  }

  show() {
    this.tooltipElement.classList.add('tooltip--active');
  }

  constructor(
    private element: ElementRef
  ) {}

  ngOnInit() {
    this.tooltipElement.className = 'tooltip';
    this.element.nativeElement.appendChild(this.tooltipElement);
    this.element.nativeElement.classList.add('tooltip-container');
  }
}

This tooltip should be hidden by default.

 

We want to toggle show/hide by mouse over the '(?)' span:

So just export the directive:

@Directive({
  selector: '[tooltip]',
  exportAs: 'tooltip'
})

 

The html:

    <div>
      <label>
        Credit Card Number
        <input 
          name="credit-card" 
          type="text"
          placeholder="Enter your 16-digit card number"
          credit-card>
      </label>
      <label
        tooltip="3 digial only"
        #myTooltip="tooltip"
        >
        Enter your security code 
        <span
          (mouseover)="myTooltip.show()"
          (mouseout)="myTooltip.hide()">
          (?)
        </span>
        <input type="text">
      </label>
    </div>

 

And html get use template ref to get the directive:

#myTooltip="tooltip"

Then we can control it in other place:

        <span
          (mouseover)="myTooltip.show()"
          (mouseout)="myTooltip.hide()">
          (?)
        </span>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值