1

I'm adding virtual slides to my swiper with swiper.js. The array that contains the slides, according to the examples, use strings like below (docs say slides: any, but I tried a component and other things, but nothing else worked):

virtual: {
  // cache: true,
  slides: (function() {
    const slides = [];
    for (let i = 0; i < 1; i += 1) {
      slides.push('<img src="https://picsum.photos/600/600/?image=1/>';
    }
    return slides;
  })()
},

Problem - I want to use a custom component 'app-member-card' as my slide instead of a string, so I add it as a string like below, but when it's rendered on the screen it doesn't interpolate/transpile/compile/render/etc the components code or HTML, the debugger shows the string I passed it.

I'd like to do this:

slides.push('<app-member-card class="router-link" [MemberCard]="member"></app-member-card>');

Where this below is what I'd see on the screen:

<div class="card member-card">
  <div class="row">...other tags left out here for verbosity</div>
</div>

Question: Is there something I can do in Angular or swiper.js that will translate this string into the component when adding it as a slide? I couldn't find anything in the swiper doc and not that familiar with all of the Angular stuff.

What I tried - I tried dynamically creating the component in my .ts file and adding the properties, but when I try and extract the innerHTML as a string from the viewContainerRef all data is empty. Here is my link to that post on SO

chuckd
  • 13,460
  • 29
  • 152
  • 331

1 Answers1

0

You're overdoing it. There's a reason for it to be "that hard" in Angular to inject HTML in it.

The answer I gave you at the other question should be enough to fulfill your desired result. However, the best approach would be to NOT store HTML. Instead, store what is needed for app-member-card to be rendered.

Something similar to this:

export interface IMemberCard{
    id: number;
    url: string;
    wSize: number;
    hSize: number;
}

...

virtual: {
  // cache: true,
  slides: (function() {
    const slides: Array<IMemberCard> = [];
    for (let i = 0; i < 1; i += 1) {
      slides.push({
        id: i + 1;
        url: 'https://picsum.photos',
        wSize: 600,
        hSize: 600
      });
    }
    return slides;
  })()
},

Then in your HTML you can render app-member-card directly:

<div class="row" *ngFor="let slide of slides">
    <app-member-card class="router-link" [MemberCard]="slide"></app-member-card>
</div>

That's just how Angular is meant to be used, the hacky-thing I posted in the other question is ok to be used as long as you don't care about maintainability. Generic/dynamic code can get messy really quick.

luiscla27
  • 4,956
  • 37
  • 49