如何将异步数据绑定到Angular中的延迟加载平滑轮播

时间:2019-09-02 10:31:51

标签: jquery angular typescript

我试图在我的Angular 8应用程序中集成光滑轮播。我尝试像此链接https://stackblitz.com/edit/angular-slick-carousel?file=src%2Fapp%2Fapp.component.ts一样延迟加载脚本。但是不会为 async 数据呈现Carousel。

光滑的轮播容器内的数据是动态的,可以从API调用中检索。

<div class="screenshots-carousel slick-container">
    <img [src]="image" *ngFor="let image of screenshots">
</div>

屏幕截图是一个异步变量

this.service.getdata(url).subscribe((response) => {
     this.screenshots = response
}

当我单击导航链接并进入页面时,轮播不会呈现,但是当我刷新页面时,我将获得预期的输出。

1 个答案:

答案 0 :(得分:0)

我不确定这是正确的方法,但这是解决方案;

<div class="screenshots-carousel slick-container">
    <img [src]="image" *ngFor="let image of screenshots">
</div>

在component.ts中

import { Component, OnInit, AfterViewInit } from '@angular/core'; 

declare var $: any;

@Component({
  templateUrl: './your.view.html'
})
export class YourComponent implements OnInit, AfterViewInit { 


  constructor(private service: YourService) { 
   }

  ngOnInit() {
    this.detectDivChanges(); 
  }

  detectDivChanges() {
    const div = document.querySelector('.slick-container');
    const config = { attributes: true, childList: true, subtree: true };
    const observer = new MutationObserver((mutation) => {
      this.homepageCardSlider();
      observer.disconnect();   // just run first change then dont listen div changes.
    });
    observer.observe(div, config);
  }

  ngAfterViewInit (){
   this.service.getdata(url).subscribe((response) => {
     this.screenshots = response });
}

homepageCardSlider() {
  if ($('.slick-container').length) {
      $('.slick-container').slick({
          infinite: true,
          slidesToShow: 1,
          slidesToScroll: 1,
          arrows: false,
          dots: true,
          centerMode: true,
      });
  }

}

}

通过这种方式,当将数据添加到div(http响应)时,您可以调用slick方法并使用当前数据渲染滑块。