Problem with patchValue and async signals in Angular when user refreshes the page

Discussão em 'Angular' iniciado por Zed, Abril 22, 2025.

  1. Zed

    Zed Guest

    I'm working with Angular's new Signals feature to manage reactive state in a form.

    Everything works fine in most cases. However, there's one issue I'm running into:

    When a user refreshes the page while on the form, the component is reloaded. The data that should populate the form is fetched asynchronously and exposed through a Signal. But the form is initialized before the signal gets its value.

    So when I call form.patchValue(...) during ngOnInit, the values from the signal are still undefined.

    I also considered using an effect() to reactively update the form when the signal changes, but according to the Angular documentation, effect() is not intended for this kind of logic.


    // user userApplication Component
    get customer(): Signal<Customer | null> {
    return this._store.customer;
    }

    // form Component

    ngOnInit(): void {
    const customer = this.userApplication.customer();
    if (customer && customer.identity) {
    const identity = customer.identity;
    this.identity.patchValue({
    title: identity.title,
    firstName: identity.firstName,

    });
    }
    }



    identity = inject(FormBuilder).group({
    title: new FormControl<string | null>(null),
    firstName: new FormControl<string>('', [Validators.required]),

    });

    Continue reading...

Compartilhe esta Página