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({
selec
Check in ngOnInit()
(inputs aren't yet set when the constructor is executed) whether the attribute has a value.
Component({
selector: 'my-dir',
template: ''
})
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