Is there a way to require an input based on another value?
I need to add an input which is required only if another input is not filled (and vice versa) using the signal-based inputs (not the @Input
decorator).
I added this behavior by adding a condition in ngOnInit
and by throwing an error if the two inputs are undefined, but I'm looking for a "better" and "clean" way to implement it. Does Angular have a built-in functionality for this kind of setup?
It's not possible to do this with Angular, as the check, whether the required inputs are present, is made during compile time, as per docs. Also it is not possible to add a condition for the input to be required. So by design, you cannot conditionally mark a field as required based on some other input.
You need to do this check manually on runtime, as you implemented it already. Note that ngOnInit()
does only check the configuration once at the initialization of the component. If you also want to check if the configuration continues to be correct if the inputs change dynamically, you should do the check in an effect.