angularionic-frameworkswiper.js

Swiper carousel is not working in component of Ionic Angular project


Swiper carousel is working fine on all pages. But not working in component.

    //app.module.ts

    import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

    @NgModule({
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
    })


    //app.component.ts
    import { register } from 'swiper/element/bundle';
    register();


    //home.page.html
    <swiper-container [slidesPerView]="5" [loop]="true" class="header-categories">
      <swiper-slide class="ion-text-center" *ngFor="let category of categories">
        <ion-button shape="round" color="light" size="large" (click)="category_products(category.id)">
          <ion-icon slot="icon-only" name="{{category.app_image}}"></ion-icon>
        </ion-button>
        <ion-label class="fs-small">{{category.name}}</ion-label>
      </swiper-slide>
    </swiper-container>



    //home.page.ts
    import { IonicSlides } from '@ionic/angular'; //For crousel
    import { SwiperOptions } from 'swiper/types';

This code is working on pages. But when I add same html and ts file code in component, then it shows this error.

error NG8001: 'swiper-container' is not a known element

Why it is not recognizing swiper tags in component, any idea?


Solution

  • Your Homepage Component must be standalone: true, if you are using angular 19 then it might be standalone by default. In that case, you should add the CUSTOM_ELEMENTS_SCHEMA to the schemas array inside the component decorator.

    @Component({
      selector: 'app-home-page',
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      standalone: true,
      ...
    })
    export class HomePageComponent {
      ...
    }
    

    If you find you are reusing the swiper component in multiple places of your application, then create a swiper component and set the same properties including the schema and use it throughout the application, by adding the component to the imports array.


    An alternative solution is if you are using the HomeComponent in the app.module.ts imports array you need to move the component to declarations array and then you can set it to standalone: false.

    @Component({
      selector: 'app-home-page',
      standalone: false,
      ...
    })
    export class HomePageComponent {
      ...
    }