In Angular 17, is there a way to trigger a component's method when a Signal is modified?

Our component is designed to monitor signals from a Service:

export class PaginationComponent {
  private readonly pageSize = this.listService.pageSize.asReadonly();

  private readonly totalCount = this.listService.totalCount.asReadonly();

  readonly pageCount = computed(() => Math.ceil(this.totalCount() / this.pageSize() || 1);

  readonly pages = signal<number[]>([]);

  constructor(
    private readonly paginationService: PaginationService,
  ) { }

  private calculatePages(): void {
    this.pages.set([]);
  }
}

The calculatePages method in the code above populates this.pages with the relevant information for pagination.

Is there a way to trigger this method automatically whenever this.pageCount changes?

Answer №1

Here's the recommended way to accomplish this:

Accessing a signal from a component

 private yourService = inject(YourService);
    localVariable: string //example
    constructor(){
     effect(()=> this.localVariable = this.yourService.yourSignal()
    }

Setting a signal

    yourService class

    public yourSignal = signal<string>('' as any);
    setYourSignalMethod(yourUpdateVariable:string){
      this.yourSignal.update(()=>yourUpdateVariable);
    }

Visit Angular Signals Guide for more information.

Answer №2

When

readonly pages = signal<number[]>([])
is used as a signal, it can be updated to reflect changes in this.pageCount().

One way to achieve this is:

  readonly pages = computed(() => this.pageCount());

Alternatively, you could also try:

readonly pageCount = computed(() => {
const pageCount = Math.ceil(this.totalCount() / this.pageSize() || 1;
this.calculatePages();
return pageCount;
}); 

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

Can a standard tuple be matched with its corresponding key?

This code snippet showcases a function that can recognize that the key "banana" cannot have the value "red": type Fruits = { banana: 'yellow' | 'green' strawberry: 'red' } const fruit = <K extends keyof Fruits>(modu ...

The parameter "path" must be a string type. Instead, we received type undefined. This issue is specific to Ionic 4 on Windows

Encountered an unexpected error that is hindering development on a Windows PC, even though building the app works fine on a Mac. The error message received is: cordova build android --stacktrace config file undefined requested for changes not found at ...

AG Grid, efficiently organizing hierarchical data with tree structures and allowing filtering at all levels, not just leaf

My grid is receiving tree formatted data, and I've noticed that when using column filters, they apply to the leaf nodes as well as show parent nodes necessary to provide a path to the leaves. I'm interested in finding a method to allow users to ...

Issue with PrimeNG DataTable contextMenu alignment inside TabView

I encountered an issue with displaying a DataTable - contextMenu when it is placed within a TabView. The contextMenu was appearing off-center. However, the DataTable - contextMenu worked perfectly fine when it was not wrapped in a TabView. To address this ...

Angular application navigation does not work as expected when the application is served in Express.js

I have an Angular 7 application that is running on an ExpressJS server. This is how the server part of the app is set up: app.get('/', (req, res) => { console.log(`sending...`); res.sendFile(path.join(__dirname, 'index.html') ...

Tips for effectively utilizing Mongoose models within Next.js

Currently, I am in the process of developing a Next.js application using TypeScript and MongoDB/Mongoose. Lately, I encountered an issue related to Mongoose models where they were attempting to overwrite the Model every time it was utilized. Here is the c ...

Is it possible to merge these two scripts into a single one within Vue?

As a newcomer to VUE, I am faced with the task of modifying some existing code. Here is my dilemma: Within a single component, there are two script tags present. One of them contains an import for useStore from the vuex library. The other script tag incl ...

Incorporating PrimeNG into your Bootstrap 4 projects

Exploring various UI libraries for a new Angular 2 project has been an interesting journey. From Ng-Bootstrap and Material to PrimeNG, each library has its own strengths and weaknesses. Currently, I find that PrimeNG offers a wider range of components comp ...

Issue with Click event not working on dynamically added button in Angular 8

My goal is to dynamically add and remove product images when a user clicks the add or delete button on the screen. However, I am encountering an issue where the function is not being called when dynamically injecting HTML and binding the click event. Below ...

Converting API response into a class instance using `class-transformer` in TypeScript: A step-by-step guide

When working with TypeScript, I have a regular method called Request(method: HttpMethod, url: string, ...) that is used for calling APIs. Now, my goal is to convert the response from this API request into an instance of a class using class-transformer (or ...

An issue has occurred: Failure to execute spawnSync PATH/target/node/node ENOENTNGCC. Please refer to the

Attempting to initiate my angular project using ./mvnw is resulting in an error when the build runs ng build --configuration development. The error message thrown reads as follows: Generating browser application bundles (phase: setup)... [INFO] /home/use ...

HashId plugin for Angular

Currently, I'm attempting to integrate into my Angular project built on the latest version. After discovering this definition file: // Type definitions for Hashids.js 1.x // Project: https://github.com/ivanakimov/hashids.node.js // Definitions by: ...

Retrieve the value of [innerHTML] from a subcomponent

I am trying to retrieve the [innerHTML] from a child component Greetings everyone There is a component named 'contact-us' containing the following field. <div [innerHTML] = "legalContent.disclaimer"></div> I have included ...

What is the process for extracting the background color from a typescript file in Angular and connecting it to my HTML document?

My typescript array population is not changing the background color of my div based on the values in the array. I've attempted to set the background using [style.backgroundColor]="statusColor[i]", where statusColor is an array declared in my typescrip ...

Tips for Validating Radio Buttons in Angular Reactive Forms and Displaying Error Messages upon Submission

Objective: Ensure that the radio buttons are mandatory. Challenge: The element mat-error and its content are being displayed immediately, even before the form is submitted. It should only show up when the user tries to submit the form. I attempted to use ...

The directive within the module was not carried out

After setting up a fresh module in my Angular 8 project and adding a new directive to it, nothing seemed to happen at runtime (although the compilation was successful). I even added console logs to the directive to check if it was being executed different ...

Transform JSON object to a class/interface object using Typescript

I am currently working on converting an API response into a TypeScript class or interface. The API is returning a list of objects with various properties, but I only require a few specific properties from the response object. Example of API Response: ...

Differences between Integrated and Isolated Testing in Angular 2

Can you explain the key distinctions between Integrated testing and Isolated testing? In what scenarios would these testing methods be recommended for use? ...

Mapping arrays from objects using Next.js and Typescript

I am trying to create a mapping for the object below using { ...product.images[0] }, { ...product.type[0] }, and { ...product.productPackages[0] } in my code snippet. This is the object I need to map: export const customImage = [ { status: false, ...

Troubleshooting problem with Angular2 installation

Can someone please shed light on the current problem I am facing with the updated version of angular-cli? It was running smoothly earlier but now it keeps showing an error message saying "The "@angular/compiler-cli" package was not properly installed." An ...