angular8 滚动多个图片加文字组件

子组件html

<div class="container" 
[ngStyle]="{
    'grid-template-rows': templateRows,
    'grid-template-columns': templateColumns}"
    (scroll) ="handleScroll($event)"
    >
    <ng-content select="[appGridItem]"></ng-content>
</div>
<div class="underline" *ngIf="scrollable">
    <div class="highlight" [ngStyle]="{'margin': sliderMargin}"></div>
</div>

子组件css

.container{
    background-color: #fff;
    padding: 5px 0;
    overflow-x: auto;
    overflow-y: hidden;
    scroll-behavior: smooth;
    -webkit-overflow-scrolling: touch;
    display: grid;
    place-content: stretch;
    place-items: center;
    grid-gap: 0.4rem;
    grid-auto-flow: row;
}
.underline {
    width: 20%;
    height: 2px;
    background-color: #f5f5f5;
    margin: 0 auto;
  }
.underline > .highlight {
    width: 50%;
    height: 2px;
    background-color: #e02f29;
    padding: 0;
}
.container::-webkit-scrollbar {
    display: none !important;
}

子组件ts

import { Component, OnInit,Output,Input} from '@angular/core';
export interface Channel {
  id: number;
  icon: string ;
  title: string;
  link: string;
}
@Component({
  selector: 'app-horizontal-grid',
  templateUrl: './horizontal-grid.component.html',
  styleUrls: ['./horizontal-grid.component.css']
})
export class HorizontalGridComponent implements OnInit {
  constructor() { }
  @Output() cols =6;
  @Input() displayCols =5;
  sliderMargin = '0'
  ngOnInit() {
  }
  
  public get scrollable() : boolean {
    return this.cols > this.displayCols
  }
  
  public get templateRows() : string {
    return `minmax(auto,max-content)`
  }
 
 public get templateColumns() : string {
   return `repeat(${this.cols},calc((100vw - ${this.displayCols*0.4}rem)/${this.displayCols}))`
 }
 handleScroll(ev){
  this.sliderMargin = `0 ${100*ev.target.scrollLeft /ev.target.scrollWidth}%`
 }
}

父组件html

<app-horizontal-grid >
    <div appGridItem *ngFor="let item of channels">
        <img [src]="item.icon" alt="" appGridItemImage="2rem" fitMode="none" (click)="handleClick(item.id)" >
        <span appGridItemTitle="0.6rem">{{ item.title }}</span>
    </div>
</app-horizontal-grid> 

可以到git下载https://github.com/yyk316507/angualr8-demo

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页