Search code examples
angularsignals

How to do some restriction with signals in angular?


i am new to signals and i am having some difficulties with understanding basics.

  public currentPage: WritableSignal<number> = signal(1);
  public totalPages: Signal<number> = computed(() => {
    return Math.max(1, Math.ceil((this.totalCount() ?? 0) / this.pageSize()));
  });

and it make sense to check if currentPages are higher than totalPages and in that case set to 1.

effect(() => {
  if (this.currentPage() > this.totalPages()) {
    this.currectPage.set(1);
  }
});

but .set in effect is not recomended and to do that i have to add { allowSignalWrites: true }, and to prevent loops untracked() but that seems weird.

What would be recomended approach to this? Am i missing something?


Solution

  • UPDATE:

    Create another computed, called, currentPageWithLimits. This will contain the same logic, and will react based on your logic.

      public currentPage: WritableSignal<number> = signal(1);
      public totalPages: Signal<number> = computed(() => {
        return Math.max(1, Math.ceil((this.totalCount() ?? 0) / this.pageSize()));
      });
      public currentPageWithLimits: Signal<number> = computed(() => {
          const currentPage = this.currentPage();
          if (currentPage > this.totalPages()) {
            return 1;
          } else {
            return currentPage;
          }
      });
    

    It's better to move this code out of the effect and into the place where you set the current page. This will solve your problem.

    Since set is not recommended inside the effect and your requirement does not seem to even require an effect as per the code provided, this is the best solution.

    setCurrentPage() {
      if (this.currentPage() > this.totalPages()) {
        this.currentPage.set(1);
      } else {
        this.currentPage.update((prev) => prev + 1);
      }
    }