子组件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>
这篇博客介绍了如何在Angular8中创建一个滚动展示多个图片和文字的组件。包括子组件的HTML、CSS和TS代码,以及父组件的HTML结构。完整代码可从GitHub仓库https://github.com/yyk316507/angualr8-demo获取。
2875

被折叠的 条评论
为什么被折叠?



