miguel gremy
miguel gremy

Reputation: 50

Conditional required input

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?

Upvotes: 1

Views: 140

Answers (3)

JSON Derulo
JSON Derulo

Reputation: 17758

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.

Upvotes: 2

Stefani Toto
Stefani Toto

Reputation: 290

You can use reactive forms and check if the specific input is valid or not and use it to the next input.

https://stackblitz.com/edit/angular-8-reactive-form-validation-oybffrk8?file=app%2Fapp.component.ts&file=app%2Fapp.component.html

Upvotes: 0

Olivier
Olivier

Reputation: 56

What about using a single required input whose model is typed in a way to make a sub-property required based on the other property's value?

Something like:

interface InputBase {
  fruitType: 'apple' | 'banana';
  fruitColor?: string; // notice that this is optionnal in the base interface
}

interface InputApple extends InputBase {
  fruitType: 'apple';
  fruitColor: string; // notice that this is now required if fruitType value is 'apple'
}

interface InputBanana extends InputBase {
}

export type InputType = InputBanana | InputApple; // this is the type you use

That way, your input would, through TypeScript validation, make sure that some property is required only if another value is x.

Upvotes: 1

Related Questions