Цикл ngFor над динамическим массивом для начальной загрузки-карусели - PullRequest
0 голосов
/ 30 мая 2019

Я хочу показать карусель, которая зацикливается на массиве, который загружается динамически из серверной части. Я хотел бы иметь многоэлементную карусель, которая, кажется, прекрасно работает для статических изображений.

Когда вместо прямой строки в src img дается, я использую переменную, которая была установлена ​​в component.ts, изображение просто загружается, когда слайд активен, в противном случае оно просто не отображается. Наконец, становится еще хуже, когда в игру вступает ngFor.

Здесь я покажу вам три поведения, которые я получаю с другим кодом:

Это component.ts со списком ссылок на изображения, которые я хочу показать:

@Component({
  selector: 'app-carrousel',
  templateUrl: './carrousel.component.html',
  styleUrls: ['./carrousel.component.scss']
})
export class CarrouselComponent implements OnInit {
 list_cards = [
    {url: 'http://placehold.it/350x180?text=1', title: 'Card 1', descrption: 'description of card 1'},
    {url: 'http://placehold.it/350x180?text=2', title: 'Card 2', descrption: 'description of card 2'},
    {url: 'http://placehold.it/350x180?text=3', title: 'Card 3', descrption: 'description of card 3'},
    {url: 'http://placehold.it/350x180?text=4', title: 'Card 4', descrption: 'description of card 4'},
    {url: 'http://placehold.it/350x180?text=5', title: 'Card 5', descrption: 'description of card 5'},
    {url: 'http://placehold.it/350x180?text=6', title: 'Card 6', descrption: 'description of card 6'}
  ];

 ngOnInit(): void {
    $('#carousel_new_items').carousel({
      interval: 2000
    });

    $('.carousel .carousel-item').each(function() {
      let next = $(this).next();
      if (!next.length) {
        next = $(this).siblings(':first');
      }
      next.children(':first-child').clone().appendTo($(this));

      for (let i = 0; i < 4; i++) {
        next = next.next();
        if (!next.length) {
          next = $(this).siblings(':first');
        }
        next.children(':first-child').clone().appendTo($(this));
      }
    });
  }

}

это component.html для поведения 1, без цикла и всего изображения src с прямой строкой:

<div id="carousel_new_items" class="carousel slide w-100" data-ride="carousel">
  <div class="carousel-item active">
    <div class="card col-3">
      <img class="card-img-top" src="http://placehold.it/350x180?text=1">
      <div class="card-body">
        <p>{{this.list_cards[0].title}}</p>
        <p>{{this.list_cards[0].descrption}}</p>
        <p>static text car 1</p>
      </div>
    </div>
  </div>
  ...
  <div class="carousel-item">
    <div class="card col-3">
      <img class="card-img-top" src="http://placehold.it/350x180?text=5">
      <div class="card-body">
        <p>{{this.list_cards[5].title}}</p>
        <p>{{this.list_cards[5].descrption}}</p>
        <p>static text car 6</p>
      </div>
    </div>
  </div>
</div>

это component.html для поведения 2, без цикла и всего изображения src со строкой из списка объектов:

<div id="carousel_new_items" class="carousel slide w-100" data-ride="carousel">
  <div class="carousel-item active">
    <div class="card col-3">
      <img class="card-img-top" src="{{this.list_cards[0].url}}">
      <div class="card-body">
        <p>{{this.list_cards[0].title}}</p>
        <p>{{this.list_cards[0].descrption}}</p>
        <p>static text car 1</p>
      </div>
    </div>
  </div>
  ...
  <div class="carousel-item">
    <div class="card col-3">
      <img class="card-img-top" src="{{this.list_cards[5].url}}">
      <div class="card-body">
        <p>{{this.list_cards[5].title}}</p>
        <p>{{this.list_cards[5].descrption}}</p>
        <p>static text car 6</p>
      </div>
    </div>
  </div>
</div>

это component.html для поведения 3, зацикливание на list_cards и всех изображениях src со строкой из списка объектов:

<div id="carousel_new_items" class="carousel slide w-100" data-ride="carousel">
  <div class="carousel-item" *ngFor="let card_item of list_cards let i= index" [ngClass]="{'active' : i == 0}">
    <div class="card col-3">
      <img class="card-img-top" src="{{card_item.url}}">
      <div class="card-body">
        <p>{{card_item.title}}</p>
        <p>{{card_item.descrption}}</p>
      </div>
    </div>
  </div>
</div>

Поведение 1 (все карты в порядке): behaviour 1, all cards ok

Поведение 2 (показывает только изображение, когда карта активна): only shows the image when the card is active

Поведение 3 (все смещено влево, показывая только активный слайд одновременно): all is shift to the left showing only the active slide at a time

Пожалуйста! Может кто-нибудь помочь мне получить код поведения 3, ведущий себя как 1? любые идеи приветствуются!

...