Recently, I started working on Angular 11 and encountered a simple yet challenging question. Despite my best efforts, I have been unable to find a suitable answer. In an attempt to utilize Object-Oriented Programming (OOP) concepts within Angular, I created a base interface with over 20 fields.
export interface IBaseOperator{
type:EOperatorType;
firstname:string;
lastname:string;
date:string;
nic:string;
// Additional fields are omitted for brevity
}
This base interface serves as the foundation for more than 6 child interfaces. While I will not list all of them here, I will provide examples:
export interface IStaff extends IBaseOperator{
empId:string;
// Additional fields
}
export interface IContractor extends IBaseOperator{
regId:string;
joinedDate:string;
// Additional fields
}
When creating a view in HTML for data input, I found myself duplicating <input>
fields for both IBaseOperator and its child interfaces in each component. This resulted in redundant code where the fields from IBaseOperator were repeated in all child components. Furthermore, the same functions for save(), update(), delete()
had to be duplicated across all 6 children, albeit with slightly different initializations. Currently, my approach is as follows:
For Staff component
this.operatorForm = this.fb.group({
firstname: ['', Validators.required],
lastname: ['', Validators.required],
date: ['', Validators.required],
nic: ['', Validators.required],
type:[EOperatorType.STAFF,Validators.required]
empId: ['', Validators.required]
});
For contractor component
this.operatorForm = this.fb.group({
firstname: ['', Validators.required],
lastname: ['', Validators.required],
date: ['', Validators.required],
nic: ['', Validators.required],
type:[EOperatorType.CONTRACTOR,Validators.required]
regId: ['', Validators.required]
joinedDate: ['', Validators.required]
});
These repetitive patterns present several challenges:
- Duplicated code across all 6 HTML and TypeScript files
- Any changes to the IBaseOperator interface necessitate modifications in all 6 components
- Wastage of time and resources due to unnecessary repetition
My query revolves around the feasibility of implementing inheritance in Angular components (both in HTML and TypeScript). Is it possible to consolidate common <input>
fields (IBaseOperator) from all child components into a single BaseComponent.html
, while also inheriting common functions from a shared BaseComponent.ts
? How can this be achieved effectively?
I eagerly await your insights and guidance. Thank you.