1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

Alternative to using effect() with "{ allowSignalWrites: true }"

Discussão em 'Angular' iniciado por Wolf359, Outubro 5, 2024 às 20:52.

  1. Wolf359

    Wolf359 Guest

    I have this component implementing ControlValueAccessor and holding the internal state in a signal value:

    export class InputComponent implements ControlValueAccessor {

    // internal state
    value = signal('');

    // implement writeValue()
    writeValue(value: string): void { this.value.set(value); } // <-- writeValue is updating the signal

    // other methods

    }


    The InputComponent is used in a template like this:

    <!-- ClientComponent template -->
    <app-input [formControl]="fcUrl"/>


    where fcUrl is a FormControl:

    export class ClientComponent {

    url = input.required<string>();
    fcUrl = new FormControl<string>('');

    constructor() {

    effect(() => {

    // update the FormControl when new value for 'url' arrives:
    this.fcUrl.setValue(this.url());

    }, { allowSignalWrites: true });

    }

    }


    Here, { allowSignalWrites: true } is necessary because the writeValue() of InputComponent is setting the value of a signal. Otherwise a runtime error is thrown :

    NG0600: Writing to signals is not allowed in a `computed` or an `effect` by default. Use `allowSignalWrites` in the `CreateEffectOptions` to enable this inside effects.


    What's the right way of updating the FormControl using an effect() without using the allowSignalWrites flag in this scenario (other than replacing the effect() with rxjs, e.g. toObservable(this.url).pipe(...)) ?

    Continue reading...

Compartilhe esta Página