I have been experimenting with signals and I am questioning whether the current use case would be more beneficial without using Signals and instead just having a "normal" class member swiper?: Swiper
:
@Component({
selector: '[app-test]',
standalone: true,
imports: [CommonModule],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class TestComponent implements AfterViewInit {
swiper = signal<Swiper|undefined>(undefined);
constructor(
private readonly cd: ChangeDetectorRef,
private readonly elementRef: ElementRef,
) { }
ngAfterViewInit(): void {
const swiper: unknown = this.elementRef.nativeElement.querySelector('swiper-container')?.swiper;
if (swiper instanceof Swiper) {
this.swiper.set(swiper);
this.cd.detectChanges();
}
}
slideTo(direction: 'prev'|'next'): void {
const swiper = this.swiper();
if (!swiper) return;
direction === 'prev' ? swiper.slidePrev() : swiper.slideNext();
}
}
And within the template:
<fieldset *ngIf="swiper() as swiper">
<button
type="button"
[attr.disabled]="swiper.activeIndex === 0 ? true : null"
(click)="slideTo('prev')"
>Prev</button>
<button
class="slider-navigation slider-navigation--next"
type="button"
[attr.disabled]="swiper.activeIndex === swiper.slides.length - 1 ? true : null"
(click)="slideTo('next')"
>Next</button>
</fieldset>
I acknowledge the need for this.cd.detectChanges();
since ngAfterViewInit
is executed after Angular's change detection. But I find myself wondering if Signals truly make a difference here, as it seems to essentially replicate not using Signals at all. What advantages do Signals offer in this scenario? Am I implementing them correctly?