首页 > 解决方案 > bxslider 在角度 6 中不能与 *ngFor 一起使用

问题描述

我在 Angular 6 中较新并使用 bxslider。它与数组一起工作正常,但我使用 *ngFor 作为动态它不起作用。如何重新初始化动态数据。

使用数组正常工作

 <div class="bxslider">
     <div *ngFor="let slide of sliders"><img [src]="slide.url"></div>
</div> 

动态不工作

 <div class="bxslider">
  <div *ngFor="let slide of banner_images"><img [src]="slide.data.image"></div>
 </div>

这些是 component.ts

import { Component, OnInit, AfterViewInit } from '@angular/core';
import { HomeHttpService } from 'src/app/shared/services/home/home- 
http.service';
declare var jquery:any;
declare var $ :any;
@Component({
selector: 'app-top-savers',
templateUrl: './top-savers.component.html',
styleUrls: ['./top-savers.component.css']
})
export class TopSaversComponent implements OnInit, AfterViewInit {

public banner_images: any[];

//static calling
public sliders : any[] = [
{"url":"image.jpg"},
{"url":"image.jpg"},
{"url":"image.jpg"},
{"url":"image.jpg"},
{"url":"image.jpg"}
   ];  

 constructor(private homeService:HomeHttpService) { }

 ngOnInit() {
    //fetching api data
    this.homeService.getBanner().subscribe((data) =>{   
    let banner = data[2]["objects"];
    this.banner_images = banner;
    //console.log(this.banner_images);
   });
  }

 ngAfterViewInit() {
   $('.bxslider').bxSlider({
     auto:true
   });
  }
 }

请找到下面的图片 https://i.imgur.com/UUp6YFk.jpg

标签: angular

解决方案


请将 OnInit 挂钩更改为 AfterViewInit。

import { Component, AfterViewInit} from "@angular/core";
declare var jquery:any;
declare var $ :any;
@Component({
  selector: "app-banner",
  templateUrl: './banner.component.html',
  styleUrls: ['./banner.component.css']
})
export class BannerComponent implements AfterViewInit {

  sliders = [
    {"url":"/images/image5.jpg"},
    {"url":"/images/image4.jpg"},
    {"url":"/images/image6.jpg"}
  ];

  constructor() {}

  ngAfterViewInit() {
    $('.slider').bxSlider({
      auto:true
    });

  }


}

推荐阅读