Angular signals react to local state changes, but not to changes from input signal

Discussão em 'Angular' iniciado por Naren Murali, Fevereiro 19, 2025.

  1. Naren Murali

    Naren Murali Guest

    I have this scenario, where the parent component will fetch user details and show then on the UI, code below:

    @Component({
    selector: 'app-root',
    imports: [Child, FormsModule],
    template: `
    <div> User Details</div>
    @if(resource.value(); as user) {
    <div> Title: {{user.title}}</div>
    <app-like-button [likes]="user.id"/>
    }
    <button (click)="refresh()">Reload User Data</button>
    `,
    })
    export class App {
    http = inject(HttpClient);
    id = signal(1);
    resource: ResourceRef<UserDetails> = rxResource({
    request: () => this.id(),
    loader: ({ request: id }: any) =>
    this.http.get<UserDetails>(
    `https://jsonplaceholder.typicode.com/todos/${id}`
    ),
    });

    refresh() {
    this.resource.reload();
    }
    }


    Similarly I have a likes component which is responsible for showing the count and the like/dislike button.

    @Component({
    selector: 'app-like-button',
    imports: [FormsModule],
    template: `
    <div> Child </div>
    <div>likes: {{likes()}}</div>
    <button (click)="like()">Like</button>
    <button (click)="unLike()">Dislike</button>
    `,
    })
    export class Child {


    // local state for this component
    likes: ModelSignal<number> = model.required<number>();

    constructor() {
    effect(() => {
    const likesCount = this.likes();
    // trigger an API call to save the like button press:
    console.log(likesCount);
    });
    }

    like() {
    this.likes.update((likesPrev: number) => likesPrev + 1);
    }

    unLike() {
    this.likes.update((likesPrev: number) => likesPrev - 1);
    }
    }


    In the below code, I have an effect which reacts to changes of the likes signal, by react I mean the changes are saved to the database using a put API call.

    The problem is that, I am using an effect which reacts to likes signal changes. So during initialization the PUT API call is called, which is not necessary.

    I would like the API to react to only local state updates of likes signal.

    Stackblitz Demo


    Expected result, is that API call ( represented by console.log) should not fire on initial load.

    Continue reading...

Compartilhe esta Página