Reputation: 7736
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?
Upvotes: 0
Views: 999
Reputation: 3604
Enum is only a set of constants. If you want to add validation ==> it have to be done in runtime, such as:
const validOptions = ['option1','option2','option3','option4','option5'];
export class DropdownComponent {
@Input() set option(v: any) {
if (validOptions.includes(v)) {
this._option = v;
} else {
// handle error
}
}
get option(): any {
return option;
}
private _option: any;
}
You may as well use some validation library, but it's still heavy. I would prefer working with types and using angular compilation strictTemplates
option often to detect wrong type assignment.
Upvotes: 2
Reputation: 156
As far as I know Angular can only help with with making that Input mandatory using the annotation @isRequired.
As about the verification of the input value I think it is okay to manually check it but I strongly recommend to use it in the ngOnChanges Angular Life Hook. That method is triggered everytime one of your @Input values are changing and you would want to make that check everytime that happens.
Upvotes: 2