angularvalidationinput

Is it possible to have conditional/dependant input parameters in Angular components?


To make usage of my Angular components easier, I would like to only allow relevant inputs on a component. Is this possible? I.e. for my component elevensies I would like this to work:

<elevensies [drink]="tea" [milk]="yes" />

or

<elevensies [drink]="water"/>

but not allow the combination:

<elevensies [drink]="water" [milk]="yes" />// Is it possible to give an error when adding "milk" to water?

Is this possible? Note: using <elevensies [oneInputToRuleThemAll]="{drink:'tea',milk:'yes'}"/> is a fallback solution but my question concerns using separate inputs

ts-file:

@Component({
  selector: "elevensies",
  ...
})
export class ElevensiesComponent {
  readonly drink= input.required<"tea"|"water">();
  readonly milk = input<"yes"|"no">();
}

Solution

  • you can use the power of generics

    export class ElevensiesComponent<T extends 'tea' | 'water'> {
      drink = input<T>();
      milk = input<T extends 'water' ? undefined : 'yes' | 'no'>()
    }
    

    this way the error of using [milk] input will be compile time error, and not runtime error

    [drink]="'water'" [milk]="yes"> // error, as yes is not assignable to undefined