🛝

angularでswiper/elementを使用するTips

2024/04/11に公開

CUSTOM_ELEMENTS_SCHEMAを使いたくない病の罹患者用

swiper-container.component
import { Component, ChangeDetectionStrategy, ChangeDetectorRef, ElementRef, NgZone, Input, OnInit } from '@angular/core';
import { SwiperContainer } from 'swiper/element';
import { SwiperOptions } from 'swiper/types';

@Component({
  template: '<ng-content></ng-content>',
  selector: 'swiper-container',
  styles: [':host { display: block; }'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SwiperContainerComponent implements OnInit {
  @Input() options!: SwiperOptions;
  protected el: SwiperContainer;
  constructor(c: ChangeDetectorRef, r: ElementRef<SwiperContainer>, protected z: NgZone) {
    c.detach();
    // https://swiperjs.com/element#parameters-as-props
    r.nativeElement.init = false;
    this.el = r.nativeElement as SwiperContainer;
  }

  ngOnInit() {
    this.z.runOutsideAngular(() => {
      Object.assign(this.el, this.options);
      this.el.initialize();
    });
  }
}
swiper-slide.component
import { Component, ChangeDetectionStrategy, ChangeDetectorRef, ElementRef, NgZone, Input } from '@angular/core';
import { SwiperSlide } from 'swiper/element';

@Component({
  selector: 'swiper-slide',
  template: '<ng-content></ng-content>',
  styles: [':host { display: block; }'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SwiperSlideComponent {
  protected el: SwiperSlide;
  constructor(c: ChangeDetectorRef, r: ElementRef<SwiperSlide>) {
    c.detach();
    this.el = r.nativeElement as SwiperSlide;
  }
}
app.component.ts
import { Component } from '@angular/core';
import { SwiperOptions } from 'swiper/types';

@Component({
  selector: 'app-root',
  template: `
    <swiper-container [options]="options">
      <swiper-slide><p>Slide 1</p></swiper-slide>
      <swiper-slide><p>Slide 2</p></swiper-slide>
      <swiper-slide><p>Slide 3</p></swiper-slide>
    </swiper-container>
  `,
  styles: []
})
export class AppComponent {
  options: SwiperOptions = {
    pagination: {
      enabled: true,
      type: 'fraction'
    }
  };
}
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { register } from 'swiper/element/bundle';

@NgModule({
  declarations: [
    AppComponent,
    SwiperContainerComponent,
    SwiperSlideComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
  constructor() {
    register();
  }
}

Discussion