I cannot find any documentation on this, but it seems like you cannot emit an event from an effect
. What is the recommended way to emit an event based on a signal value changing?
I have a simple component:
class SimpleComponent {
@Output countChanged: EventEmitter<number> = new EventEmitter<number>();
constructor() {
this.form = this.formBuilder.group({
totalCount: new FormControl<number>(0),
});
// we want to output an event when the form value changes
const formSelection = toSignal(this.form.get('totalCount').valueChanges, { initialValue: 0 });
effect(() => {
const selection = formSelection()
if (selection != 0) {
this.countChanged.emit(selection) // call fails
}
});
}
}
The above code logs ‘writing to signals is not allowed in a computed
or an effect
‘, and an event is not emitted.
What is the recommended way to use EventEmitters with signals? Or am I doing something wrong?
I can work around this by either setting { allowSignalWrites: true }
as a param to the effect call. Another option is to use untracked(this.countChange.emit(selection)
.
However, I’m not sure if either is recommended. I’m assuming this would be a common use-case with angular signals.
Brendan Goldacker is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.