0

I've imported owl-carousel libraries into my Angular2 CLI project, which displays correctly if I have:

<div class="owl-carousel owl-theme" #carousel >
    <div>item</div>
    <div>item</div>
    <div>item</div>
    <div>item</div>
</div>

but I need the data for the carousel to load asynchronously. So in my component's typescript I've updated to:

...
this.getData().subscribe(
        d => {
            this.data = <Results>d;
        },
        error => {
            console.log(error);
        });
...

Then in my html for the component I now have:

<div class="owl-carousel owl-theme" #carousel >
    <div *ngFor="let item of data.items">
          <h1>Item name</h1>
          {{item.name}}
      </div>
</div>

However it doesn't display correctly. The data is loaded but the carousel doesn't set itself up properly. I've experimented with calling the element's owlCarousel() after the data has loaded but still didn't fix it.

I'm not sure what I'm doing wrong, anyone know how to fix this?

Hallupa
  • 1,155
  • 1
  • 9
  • 14
  • How do you initialize plugin? – yurzui Jun 13 '17 at 19:56
  • I installed owl.carousel using npm install --save owl.carousel then imported the js and styles. I initialise the carousel using this.owlElement = jQuery('.owl-carousel'); this.owlElement.owlCarousel(); – Hallupa Jun 13 '17 at 20:16
  • 1
    Try running `cdRef.detectChanges()` after `this.data = d;` and then call `this.owlElement.owlCarousel()` See also https://stackoverflow.com/questions/43457149/angular-4-what-is-the-right-way-to-wait-for-operation – yurzui Jun 13 '17 at 20:19
  • Coul it be because you're selecting one `item` from the `data` variable to itterate? `
    `?
    – Prav Jun 13 '17 at 20:24
  • Thanks yurzil! calling cdRef.detectChanges() fixed it. If you add that as the answer I'll mark it as the answer – Hallupa Jun 13 '17 at 20:36

1 Answers1

0

It looks like you can initialise the carousel in ngAfterViewInit() rather than detecting change and updating the DOM.

Also think about clearing the carousel object in ngOnDestroy().

Someone else's example here: plunkr example

joedev
  • 65
  • 5