Am I utilizing Angular's signals correctly? And what is the purpose of still requiring ChangeDetectorRef.detectChanges()?

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?

Answer №1

Upon conducting a thorough investigation as a team, we discovered that the issue in both versions of the code stems from the Change Detection cycle concluding after setting a signal.

This is why markForCheck() is ineffective (as the signal already marks the views), while detectChanges() proves successful - requiring an additional CD cycle to inspect all marked views.

Validated by Alex Rickabaugh.


Prior response:

Your code can be accessed on StackBlitz here: https://stackblitz.com/edit/stackblitz-starters-1tnwzf?file=src%2Fmain.ts

It functions without requiring a cd.detectChanges() invocation. It simply outputs a well-known error to the console in development mode ;)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular 8 date validation for start date and end date on a mat-date-picker

My current task involves working with the Mat date picker, specifically focusing on setting up validation rules for start and end dates. One important rule to note is that the end date should always be after or equal to the start date. For instance: If th ...

What is the best method to retrieve the value of a cell in a different cell within the same row in an Angular Material Data-Table?

I am working with an Angular Material Data Table that has four columns. In every row, the last cell contains a button with an on-click function attached to it. I need to pass the value from the first cell ("Name") as a parameter in the corresponding button ...

Why is it that in Angular, console.log(11) is displayed before console.log(1)?

Can someone help me understand why my simple submit method is printing Console.log(11) before Console.log(1)? I'm confused about the order of execution. submit(value) { this.secServise.getUserById(this.currentUser.mgId).subscribe( uAddrs => { ...

Error encountered while fetching client credentials in Next-Auth Credential-Provider [next-auth]

Exploring the combination of nextjs and next-auth for authentication using a credential provider has been intriguing. However, I've encountered an issue when attempting to access a protected route while logged in: [next-auth][error][client_fetch_error ...

Javascript/Typescript Performance Evaluation

I am looking to create a visual report in the form of a table that displays the count of each rating based on the date. The ratings are based on a scale of 1 to 5. Below is the object containing the data: [ { "Date": "01/11/2022", ...

What method can be used to fetch generic type parameter in typescript?

I am having trouble finding the type of E within the code provided below. class A<E> { getParameterType() { // I need to determine the type of E } } class B { } ** Example ** new A<number>().getParameterType() // number new A<B&g ...

What is the best way to utilize the features of component A within component B when they exist as separate entities

Component A has all the necessary functionalities, and I want to use it in Component B. The code for ComponentA.ts is extensive, but it's not written in a service. How can I utilize the logic from Component A without using a service, considering both ...

Exploring the world of nested observables in Angular through cascading HTTP requests

My plan involves the following steps: Make a request to https://reqres.in/api/users/2 This request will return the following response. { "data": { "id": 2, "first_name": "Janet", "last_name": "Weaver", "avatar": "https://s3.ama ...

Tips for displaying backend error messages on the frontend

I am facing an issue with returning error messages from the backend to the frontend in my Angular project. The specific requirement is to display an error message when the value of msisdn is not eligible for renewal. Currently, the hardcoded error message ...

Tips on integrating Ionic 2 with Angular 2 services

I'm a beginner with Ionic 2. I came across information in the Angular 2 documentation stating that services need to be injected during application bootstrapping. However, I didn't see any mention of bootstrapping while following the Ionic 2 tuto ...

How can I exclude *.d.ts files from tslint checking?

Recently, I decided to integrate tslint into my workflow. Following the installation steps, I used the command: npm install tslint tslint-config-ms-recommended --save-dev My configuration file tslint.json now looks like this: { "extends": "tslint-co ...

The latest update of WebStorm in 2016.3 has brought to light an error related to the experimental support for decorators, which may undergo changes in forthcoming

Hello, I recently updated to the latest WebStorm version and encountered this error message: Error:(52, 14) TS1219:Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' ...

Unable to install Angular to the most recent version

Can anyone help me with installing Angular 16? I've tried various solutions on GitHub and Stack Overflow, but I always end up with Angular 15.2.9. This problem occurs on my Windows 11 machine, while on my MacBook, I have successfully installed Angula ...

What is the reason for Jest attempting to resolve all components in my index.ts file?

Having a bit of trouble while using Jest (with Enzyme) to test my Typescript-React project due to an issue with an alias module. The module is being found correctly, but I believe the problem may lie in the structure of one of my files. In my jest.config ...

Guide to accessing and modifying attributes of Ionic components in TypeScript file

I am curious about how to manipulate the properties or attributes of an Ionic component from a TypeScript file. For example, if I have an input component on my HTML page: <ion-item> <ion-input type="text" [(ngModel)]="testText"></ion ...

Identify the general type according to a boolean property for a React element

Currently, I am facing a scenario where I need to handle two different cases using the same component depending on a boolean value. The technologies I am working with include React, Typescript, and Formik. In one case, I have a simple select box where th ...

Error in Angular production build due to Clean CSS failure

Encountering the following error during the code build process, any solutions? > ng build --prod --no-aot --base-href 92% chunk asset optimizationD:\myproject\node_modules\@angular\cli\node_modules\clean-css\lib&bsol ...

Obtain the data from a promise in Angular

I have a function that returns a Promise, and within that Promise, I receive an object in the resolve. Below is the function from my service that is functioning correctly. buscarUsuario(email: string){ return new Promise((resolve, reject) => { this.ht ...

Encountering NoResourceAdapterError when using @admin-bro/nestjs alongside @admin-bro/sequelize and MySQL?

Encountering a similar issue with '@admin-bro/sequelize' NoResourceAdapterError: No compatible adapters found for the provided resource import { Database, Resource } from '@admin-bro/sequelize'; import { AdminModule } from '@admin- ...

Using the `import.meta` meta-property is restricted to the `es2020`, `esnext`, or `system` options in snowpack+testing-library and will result in an error

I've been encountering issues while setting up Jest and React Testing Library for the snowpack project. The error message I'm receiving is "The 'import.meta' meta-property is only allowed when the '--module' option is 'es ...