Angular+Typescript 學習筆記(三)---viewChild

viewChild

使用 viewchild 等開發了一個輪播圖組件
html

<div class="container">
  <div class="image-slider" (scroll)="handleScroll($event)" #imageSlider>
    <img *ngFor="let slider of sliders" [src]="slider.imgUrl" [alt]="slider.caption">
  </div>
  <div class="nav-section">
    <span [ngClass]="{'select-button-select':idx === selectIndex}" *ngFor="let _ of sliders;let idx = index;" class="select-button">
    </span>
  </div>
</div>

ts

import { Component, OnInit, Input, ViewChild, ElementRef, ViewChildren, QueryList, Renderer2, AfterViewInit, OnDestroy } from '@angular/core';

export interface ImageSlider {
  imgUrl: string;
  link: string;
  caption: string;
}
@Component({
  selector: 'app-image-slider',
  templateUrl: './image-slider.component.html',
  styleUrls: ['./image-slider.component.less']
})
export class ImageSliderComponent implements OnInit, AfterViewInit, OnDestroy {
  @Input() sliders: ImageSlider[] = [];
  @ViewChild('imageSlider', { static: true }) imgSlider: ElementRef;
  @Input() intervalBySecond = 2;
  public intervalId: any;
  public selectIndex = 0;
  constructor(private rd2: Renderer2) { }

  ngOnInit(): void {
    // this.imgs.forEach(item => (item.nativeElement.style.height = '100px'));
  }
  ngAfterViewInit(): void {
    this.intervalId = setInterval(() => {
      this.rd2.setProperty(this.imgSlider.nativeElement,
        'scrollLeft',
        ((this.getIndex(++this.selectIndex) % this.sliders.length) * this.imgSlider.nativeElement.scrollWidth) / this.sliders.length);
    }, this.intervalBySecond * 1000);
  }
  getIndex(idx: number): number {
    return idx >= 0 ? idx : this.sliders.length - (Math.abs(idx) % this.sliders.length);
  }
  handleScroll(ev) {
    const radio = ev.target.scrollLeft * this.sliders.length / ev.target.scrollWidth;
    this.selectIndex = Math.round(radio);
  }
  ngOnDestroy(): void {
    clearInterval(this.intervalId)
  }

}

css

.container {
  position: relative;
  overflow: hidden;
}

.image-slider {
  display: flex;
  overflow-x: scroll;
  scroll-behavior: smooth;
  -webkit-overflow-scrolling: touch;
  scroll-snap-type: x mandatory;
}

.image-slider img {
  width: 100%;
  height: 160px;
}

.nav-section {
  position: absolute;
  bottom: 0;
  width: 100%;
  opacity: .5;
  color: #fff;
  background-color: #000;
  display: flex;
  justify-content: flex-end;
  align-items: stretch;
}

.nav-section .select-button {
  display: flex;
  width: 10px;
  height: 10px;
  background-color: #fff;
  text-decoration: none;
  border-radius: 5px;
  margin: 5px;
}

.nav-section .select-button-select {
  background-color: red;
}

ImageSlider 爲外部傳入的數據

Tips

設置滾動條媳婦效果:

scroll-behavior: smooth;//平滑滾動
-webkit-overflow-scrolling: touch;//屬性控制元素在移動設備上是否使用滾動回彈效果.
scroll-snap-type: x mandatory;滾動吸附(需深入學習)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章