Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 422
Hely Saul Oberto Avatar asked Sep 15 '17 18:09

Hely Saul Oberto


2 Answers

try this:

@Input() type: 'acceptable1' | 'acceptable2' | 'acceptable3';

This uses the typescript union type allowing any of the listed types. a or b or c etc

or use a TS enum

like image 65
rjustin Avatar answered Oct 02 '22 01:10

rjustin


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;
like image 27
Suren Srapyan Avatar answered Oct 02 '22 00:10

Suren Srapyan