Angular
Angular is an MVC framework built with JavaScript and Typescript.
Making a Directive Input Requiredโ
Options:
Add the inputs as part of a selector
@Component({
selector: 'app-directive[a]'
})Check required fields during
ngOnInit()
andngOnChanges()
@Component({})
export class MyComponent implements OnInit, OnChanges {
@Input() a: string;
@Input() b: number;
ngOnInit(): void {
this.checkRequiredFields();
}
ngOnChanges(): void {
this.checkRequiredFields();
}
checkRequiredFields(): void {
this.checkField('a', this.a);
this.checkField('b', this.b);
}
checkField(name: string, input: any): void {
if (input === null | input === undefined) {
throw new Error(`Attribute '${name}' is required`);
}
}
}Create a
Required
decoratorfunction Required(target: object, propertyKey: string) {
Object.defineProperty(target, propertyKey, {
get() {
throw new Error(`Attribute ${propertyKey} is required`);
},
set(value) {
Object.defineProperty(target, propertyKey, {
value,
writable: true,
configurable: true,
});
},
configurable: true
});
}โฆthen assign the decorator to the field.
@Input @Required a: string;