angular动态隐藏和添加元素

需求:在指定大小的div内,展示标签,超出范围的标签需要隐藏,并以省略号代替。因每个标签的长度不定,所以可展示的最大标签数也不定。效果如下:



问题:1.隐藏多余的标签;2.添加省略号;


方案:1.判断当前标签是否超出范围,如果超出,通过ElementRef将其隐藏;

           2.通过Renderer2渲染新创建的元素;

           可将这些逻辑封装到指令中,具体代码如下:

<div class="preCrowd-tags bf-1">
   <ul class="db bw-w bp-c">
      <li *ngFor="let tag of crowd.tags" class="tag-wrap" is-hidden >{{tag}}</li>
   </ul>
</div>

import { Directive, ElementRef, AfterViewChecked, Renderer2, Inject } from "@angular/core";
import { DOCUMENT } from '@angular/common';

declare let $;
@Directive(
  { selector: '[is-hidden]' }
)
export class IsHiddenDirective implements AfterViewChecked {
  constructor(public el: ElementRef, public render: Renderer2, @Inject(DOCUMENT) private document) {

  }
  ngAfterViewChecked() {
    if ((this.el.nativeElement.offsetTop + this.el.nativeElement.offsetHeight > $('.preCrowd-tags').height())) {
      //隐藏多余标签
      this.el.nativeElement.style.display = 'none';

      //添加省略号
      if ($('#dotli').length <= 0) {
        const child = document.createElement('li');
        child.setAttribute('id', 'dotli');
        child.style.lineHeight = '25px';
        child.style.fontSize = '18px';
        child.style.fontWeight = 'bold';
        child.innerText = '...';
        this.render.appendChild(this.el.nativeElement.parentElement, child);
      }
    }
  }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值