How can you add validation to @Input in angular so that angular throws an error when you provide an @Input that is not in the options you provided. I tried using enums, but enums can not validate variables from the template.
My current working implementation is using if statements. For example:
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'dropdown',
templateUrl: './dropdown.component.html',
styleUrls: ['./dropdown.component.scss']
})
export class DropdownComponent implements OnInit {
@Input() option;
validOptions = ['option1','option2','option3','option4','option5'];
constructor() { }
ngOnInit() {
this.validateOptionInput()
}
validateOptionInput(){
this.validOptions.forEach(myFunction);
function myFunction(value) {
if((this.validOptions != value){
throw({error: `${value} is not a valid input variable. The valid options are: ${this.validOptions}`})
} else {
return;
}
}
}
}
Is there a way to do the same using enums or a way built in, in angular?
OnInithook,optionis an Input, therefore, its value can be laterif((this.validOptions =! value).. which needs to be likeif(this.validOptions != value)