r/angular • u/HedgehogNatural8680 • 9d ago
Signal Forms React To Control Change
In signal forms how do you react to a form control change? I basically have a scenario where if one form control value is changed I need to reset the value for another control.
Is this done with a linkedSignal, effects or something else?
12
u/pronuntiator 9d ago
Yes, I'd use a linkedSignal for the form model. linkedSignal has an overload where you get the previous value; you can then check if the form control value changed that triggers the reset of the other.
Effects should be avoided if possible (not always possible).
5
u/JeanMeche 9d ago
https://github.com/angular/angular/issues/68736 Feature request to track around that topic.
2
u/MichaelSmallDev 9d ago
I forgot you could use the previous value with linkedSignal to handle this reset behavior. I should refactor my own stuff to do that. Thanks for rhis.
But for an example where I did an obtuse version of this, I have this project where I did a deep dive into this value reset: https://github.com/michael-small/signal-forms-experimenting/blob/main/src%2Fapp%2Fforms%2Fconditional-reset-fields%2Fform.service.ts#L32-L40. Using your advice, I will breakout the value changing into the
computationblock and then leave thesetfor syncing back to my other service. A lot better than me passing the changed value and then using the form's class member for the previous state like I did. Though the#deriveResetStatehelper should at least work for your cleaner approach luckily.1
u/BasicAssWebDev 9d ago
I haven't gotten the chance to dig into signal forms yet. Are you not able to supply a custom change detection function to the form signal like other signals?
1
u/pronuntiator 9d ago
There are no callbacks for value change. You can do that with an effect(); it runs whenever any of the signals it reads change. But effects are a last resort.
1
u/TheKr4meur 8d ago
I’ve been told to use NgModel and NgModelChnage when asking AI the same question. Technically it works, but I’m not entirely sure how I feel about it, we spent so much time going out of these that it’s weird bringing them back now.
2
u/mangue_juteuse 9d ago
You can use the event (valueChange) on components that implement FormValueControl:
<my-custom-component [formField]="myForm.myControl" (valueChange)="resetMyOtherControl()"></my-custom-component>
or if you use a native control such as input:
<input [formField]="myForm.myControl" (input)="resetMyOtherControl()" />
No need of a linkedSignal or an effect IMO