Issue
In AngularJs we could make a directive attribute required. How do we do that in Angular with @Input? The docs don't mention it.
Eg.
@Component({
selector: 'my-dir',
template: '<div></div>'
})
export class MyComponent {
@Input() a: number; // Make this a required attribute. Throw an exception if it doesn't exist.
@Input() b: number;
}
Solution
Check in ngOnInit() (inputs aren't yet set when the constructor is executed) whether the attribute has a value.
Component({
selector: 'my-dir',
template: '<div></div>'
})
export class MyComponent implements OnInit, OnChanges {
@Input() a:number; // Make this a required attribute. Throw an exception if it doesnt exist
@Input() b:number;
constructor(){
}
ngOnInit() {
this.checkRequiredFields(this.a);
}
ngOnChanges(changes) {
this.checkRequiredFields(this.a);
}
checkRequiredFields(input) {
if(input === null) {
throw new Error("Attribute 'a' is required");
}
}
}
You might also check in ngOnChanges(changes) {...} if the values wasn't set to null. See also https://angular.io/docs/ts/latest/api/core/OnChanges-interface.html
Answered By - Günter Zöchbauer
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.