angulartypescriptparametersenums

How to accept only predefined values in an Angular @Input


My problem here is that I receive a string value in a as a parameter to a component, but I want to limit the values that can be used as a parameter, just like an enum

I use

@Input() type: string = '';

But the in the component, everything can be introduced to the type property and I need to limit that to just 3 options, as I said before, like an Enum


Solution

  • Create an Enum and set the type of your input to the enum. Your value will be passed if it is one of the values in enum, otherwise it will be undefined

    enum MyEnum {
        First,
        Second,
        Third
    }
    
    @Input() type: MyEnum;