首页 > 解决方案 > 如何通过循环触发锚点列表的点击事件 - 在angular2中

问题描述

我正在尝试为 Angular 应用程序制作我们的团队滑块。我的场景是获取一个锚元素列表,并在触发点击之前稍微延迟地遍历它们(每次点击都会调用下一个滑块)。

接下来将显示我想要转换为 Angular 的 JS 代码 =>。

codepen上提供的源代码

注意:由于某种原因,前两张幻灯片是空的,没关系
HTML

<div id="slider">
  
<div id="0" class="SlideContainer">
.. empty
  <a href="#1">Click Me 0</a>
</div>
  
<div id="1" class="SlideContainer">
.. empty
  <a href="#2">Click Me 1</a>
</div>
  
<!-- angular ngFor starts from here => -->
<div id="2" class="SlideContainer">
  <div class="img">
<img src="https://www.nicepng.com/png/detail/11-112605_punk-cat-berkley-cats-illustrations.png">
</div>
  <a href="#3">Click Me 2</a>
</div>

  ......... etc

</div>

CSS

#slider {
  border: solid 1px #000;
  height: 500px;
  padding: .5%;
  margin: 0;
  overflow: hidden;
  white-space: nowrap;
  scroll-behavior: smooth;
}

.SlideContainer{ 
  vertical-align: top;
  border: solid 1px #000;
  height: 99% ;
  width: 33%;
  margin: .5% 0;
  display: inline-block;
}
.SlideContainer a{
  display: none;
}

.img {
  overflow: hidden; 
  max-width:200px;
  max-height:200px;
  border-radius: 50%;
  display: block;
  margin: 10px auto 0 auto;
  text-align: center;
}
.img img{
  height: 200px;
  width: 200px;
}

JS

var i = 3;                
var listA = document.getElementsByTagName("a");
var timer;

function SlideLoop() { 
  timer = setTimeout(() => {     
    listA[i].click();                 
    if (i < 12) 
       {i++}
    else
       {i = 1}  
    SlideLoop();
  }, 2000);
};

SlideLoop();

现在我只需要在 Angular TS 中应用相同的 JS 场景。这是我在 Angular 中的尝试

TS

constructor(
  private slidesHref: ElementRef,
  @Inject(DOCUMENT) private _document: HTMLDocument
  ) {}

  // attempt 1
  elements = this.slidesHref.nativeElement.querySelectorAll('.SlideContainer a');
  // attempt 2
  elem = this._document.querySelectorAll('.SlideContainer a');
  
  ngOnInit(){
    this.elements[4].click();
    this.elems.forEach(e => e.dispatchEvent(new Event('click')));
}

再说一遍:我需要获取锚点列表并使用循环和触发单击来遍历它们,如 JS 代码示例中所示,但使用 Angular(TS)。

标签: angulartypescript

解决方案


推荐阅读