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
The official Angular way to do this is to include the required properties in the selector for your component. So, something like:
Component({
selector: 'my-dir[a]', // <-- Check it
template: ''
})
export class MyComponent {
@Input() a:number; // This property is required by virtue of the selector above
@Input() b:number; // This property is still optional, but could be added to the selector to require it
constructor(){
}
ngOnInit() {
}
}
The advantage to this is that if a developer does not include the property (a
) when referencing the component in their template, the code won't compile. This means compile-time safety instead of run-time safety, which is nice.
The bummer is that the error message the developer will receive is "my-dir
is not a known element", which isn't super clear.
I tried the decorator approach mentioned by ihor, and I ran into issues since it applies to the Class (and therefore after TS compilation to the prototype), not to the instance; this meant that the decorator only runs once for all copies of a component, or at least I couldn't find a way to make it work for multiple instances.
Here are the docs for the selector option. Note that it actually allows very flexible CSS-style selector-ing (sweet word).
I found this recommendation on a Github feature request thread.