【问题标题】:ngFor rendering items on top of each other in resposive carouselngFor 在响应式轮播中将项目相互叠加
【发布时间】:2021-11-23 14:59:17
【问题描述】:

我正在使用 Angular 11 和 https://www.npmjs.com/package/angular-responsive-carousel 响应式轮播。旋转木马使用数组填充了垫卡。但是当页面第一次加载时,所有卡片都呈现在彼此之上,如图所示here

但它应该看起来像this

但是在调整窗口大小并恢复到原始大小后,轮播渲染得很好。我想找到一种方法让卡片一开始就正确渲染。

HTML 代码如下所示

<carousel [dots]="true" [cellsToShow]=cellsToShow [height]="carouselHeight" [autoplay]="false"
        [autoplayInterval]="2000"
        [borderRadius]="2" [pauseOnHover]="true">
<div class="carousel-cell" *ngFor="let item of cards; index as i; trackBy: fun">
  <mat-card class="example-card mat-elevation-z0">
    <mat-card-header>
      <a mat-card-avatar class="example-header-image" [href]="telegramUrl" target="_blank"</a>
      <mat-card-title><b>Ultime Offerte</b></mat-card-title>
      <mat-card-subtitle><i>Di Offerte Nerd</i></mat-card-subtitle>
    </mat-card-header>
    <br>
    <div class="example-card-image"><img mat-card-image [src]=item[0] alt=""></div>
    <mat-card-content>
      <div [innerHTML]="item[1]"></div>
      <br>
      {{item[2]}} <a href="{{item[3]}}" target="_blank">{{item[3]}}</a>
    </mat-card-content>
  </mat-card>
</div>

CSS 看起来像这样。

.carousel{
  position: relative;
  z-index: 1;
  padding-left: 10%;
  padding-right: 10%;
}

.carousel-cells{
  height: auto !important;
}

.carousel-cell{
  height: auto !important;
}

.example-card {
  max-width: 70vw;
  text-align: left;
  overflow-wrap: break-word;
  height: auto !important;
  border-style: solid;
  border-width: thin;
}

【问题讨论】:

    标签: javascript html css angular


    【解决方案1】:

    这只是我的猜测,但请尝试在您使用轮播的组件的 ngAfterViewInit() 生命周期挂钩中调用 cdRef.markForCheck()

    import { Component, AfterViewInit, ChangeDetectorRef } from '@angular/core';
    
    @Component({
      ...
    })
    export class MyComponent implements AfterViewInit {
      constructor(private cdRef: ChangeDetectorRef) {}
    
      ngAfterViewInit(): void {
        this.cdRef.markForCheck();
        // also try this.cdRef.detectChanges(); instead of the above
      }
    }
    

    但更好的是在您提供给轮播的数据准备就绪时触发更改检测。

    【讨论】:

      【解决方案2】:

      这是因为轮播在数据添加到卡片之前呈现。由于轮播渲染期间没有数据,轮播单元格不会占用轮播内部的实际宽度。

      对此有一个简单的解决方案。我们需要为轮播单元格提供默认宽度。可以通过添加包中提供的属性来完成。 '细胞宽度'。参考以下代码。

      <carousel [cellsToShow]=5 [cellWidth]=250 [arrows]=false>
            <div> Your content </div>
       </carousel>
      

      由于该属性支持属性绑定,我们可以尝试根据 typeScript 文件中的屏幕大小给出单元格的宽度。我没有尝试过,但上面的代码适用于我的笔记本电脑屏幕。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-21
        • 2014-09-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多