I'm using the ngx-slick-carousel module to create a carousel in my Angular 8 app. Everything works well when I call the directive from my html template,
e.g. <ngx-slick-carousel class="carousel" #slickModal="slick-carousel" [config]="slideConfig">[...]</ngx-slick-carousel>
.
However now, I want to create a carousel dynamically and include it in an [innerHtml]
which runs a pipe to override Angular sanitizer. Here is what my code looks like.
foo.component.html:
<div class="dynamic-content" [innerHtml]="dynamicHtml | safeHtml">
</div>
foo.component.ts:
// Imports
[...]
@Component({
selector: 'app-foo',
templateUrl: './foo.component.html',
styleUrls: ['./foo.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class FooComponent implements OnInit {
constructor(
[...]
) {
}
slideConfig = {
slidesToScroll: 1,
nextArrow: ('.next'),
prevArrow: ('.prev'),
infinite: false,
swipeToSlide: true
};
public dynamicHtml = '';
// This method is called at some point
public createDynamicContent(condition) {
if (condition) {
this.dynamicHtml = `
<ngx-slick-carousel class="carousel" #slickModal="slick-carousel" [config]="slideConfig">
<div ngxSlickItem>
<!-- Some stuff inside the slide -->
</div>
<div ngxSlickItem>
<!-- Some stuff inside the slide -->
</div>
<div ngxSlickItem>
<!-- Some stuff inside the slide -->
</div>
</ngx-slick-carousel>`;
} else {
this.dynamicHtml = `<p><strong>Just some simple html</strong></p>`;
}
}
}
Note: the SlickCarouselModule
is imported in my app.modules.ts
file, to allow myself to use it in all my components.
From what I understand, the issue is that the carousel is initialized when the component is initialized, and at that point, my carousel does not exist yet. My question would be: how do I dynamically create a ngx-slick-carousel?
Attempts so far
After looking into the node_modules
folder and trying to understand the code for the module, I tried to manually trigger the carousel initialization by adding the following code to my foo.component.ts
:
import { SlickCarouselComponent } from 'ngx-slick-carousel';
[...]
@ViewChild(SlickCarouselComponent, {static: false})
public slickCarousel: SlickCarouselComponent = new SlickCarouselComponent();
[...]
// This method is called at some point
public createDynamicContent(condition) {
if (condition) {
this.dynamicHtml = [...];
this.slickCarousel.initSlick();
}
}
I obtained an error in my console: this.slickCarousel.initSlick() is undefined
.