Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Angular How-to: Simplify Components with TypeScript Inheritance

Laurie Atkinson, Senior Consultant, By moving shared functionality to a base Component and assigning dependencies inside the body of the constructor, you can simplify child components.


If your Angular components contain identical or similar functionality and you find yourself copying and pasting that code, it makes sense to implement some Class inheritance, which is available with TypeScript. And, you can simplify the child components even further by removing the dependencies from the parent constructor arguments and manually assigning them inside the constructor.

Create the base component

In this example, we have 2 services that are used in the base class and are assigned using dependency injection.

base.component.ts


@Component({
    template: ''
})
export class BaseComponent {

    constructor(protected utilitiesService: UtilitiesService,
        protected loggingService: LoggingService) {
        this.logNavigation();
    }

    protected logError(errorMessage: string) { . . .}
    private logNavigation() { . . .}
}



Inherit child component from base component

Note that our child component must pass all parent dependencies into the constructor to extend it.

child.component.ts


    @Component({ . . . })

    export class ChildComponent extends BaseComponent {
    
    constructor(private childDataService: ChildDataService,
    
    utilitiesService: UtilitiesService,
    
                  loggingService: LoggingService) {
    
    super(utilitiesService, loggingService);
    
      }
    
    }    


As you can see, with a substantially complex base class, the child classes will potentially need to include a much longer list of all its parent’s dependencies. And if the parent introduces a new dependency, then all children must be updated. This may be fine, but if you want to simplify the child classes as much as possible, then take a look at this alternative.

Use a class to store the injector

This class will hold the module’s injector. It will be set once and retrieved whenever a component or service needs to get a service dependency.

app-injector.service.ts


    import { Injector } from '@angular/core';

    export class AppInjector {
    
    private static injector: Injector;
    
    static setInjector(injector: Injector) {
    
            AppInjector.injector = injector;
    
        }
    
    static getInjector(): Injector {
    
    return AppInjector.injector;
    
        }
    
    }       


After the module has been bootstrapped, store the module’s injector in the AppInjector class.

main.ts


    platformBrowserDynamic().bootstrapModule(AppModule).then((moduleRef) => {
        AppInjector.setInjector(moduleRef.injector);
    });        



Use this injector class to assign dependencies

Now, we can modify the base component to remove all constructor arguments.

base.component.ts


    @Component({
        template: ''
    })    
    export class BaseComponent {    
        protected utilitiesService: UtilitiesService;    
        protected loggingService: LoggingService;
    
    constructor() {    
            // Manually retrieve the dependencies from the injector    
            // so that constructor has no dependencies that must be passed in from child    
            const injector = AppInjector.getInjector();    
            this.utilitiesService = injector.get(UtilitiesService);    
            this.loggingService = injector.get(LoggingService);    
            this.logNavigation();
    
        }
    
        protected logError(errorMessage: string) { . . . }    
        private logNavigation() { . . . }
    }         



Inherit child component from base component

Now the child component only needs to use dependency injection for its own dependencies.

child.component.ts


    @Component({ . . . })
    export class ChildComponent extends BaseComponent {
    
    constructor(private childDataService: ChildDataService) {    
        super();    
      }    
    }            



Use the power of polymorphism to maximize code reuse

For maximum reuse of code, do not limit the methods in the parent class to merely those with identical implementations. Maybe you can refactor a complex method into pieces where shared logic can be moved into the parent. Maybe a method shares most of the logic with another component, but a few pieces differ between components which could be implemented in each child.

TypeScript inheritance allows you to override a parent method in the child class and if the parent calls that method, the child’s implementation will be invoked. For example, follow the order of execution shown in this picture, starting with a call to methodA() in ChildComponent.

Here is a non-trivial code example to illustrate the power of this feature. This application contains many pages, each comprised of a form. All these form pages share the following functionality:

  • only allow editing if the user has permission
  • save changes via a call to an API service
  • prompt the user if attempting to navigate away and there are unsaved changes

Build a form base component

form.component.ts


    @Component({
        template: ''
    })
    export class BaseFormComponent extends BaseComponent implements OnInit {
    
        updatePermission = 'UPDATE_FULL'; // Can override in child component
    
        protected routeParamName: string; // value always set in child
    
        protected entity: IEntity; // data on the form
    
        protected original: IEntity; // data before any changes are made
    
        protected dataService: EntityDataService; // service with http methods
    
        protected updateService: UpdateService;
    
        protected authorizationService: AuthorizationService;
    
        @ViewChild('confirmationDialog') confirmationDialog: ConfirmDialogComponent;
    
        constructor(protected route: ActivatedRoute) {
            super(); // call parent constructor
            const injector = AppInjector.getInjector();
            this.updateService = injector.get(UpdateService);
            this.authorizationService = injector.get(AuthorizationService);
        }
    
        ngOnInit() {
            this.route.data.subscribe(data => { // data from route resolver
                this.entity = data[this.routeParamName]; // routeParamName from child
                . . .
                this.additionalFormInitialize(); // optional initialization in child
            });
        }
    
        protected additionalFormInitialize() { // hook for child
    
        }
    
        // Child could override this method for alternate implementation
    
        hasChanged() { return !UtilitiesService.isEqual(this.original, this.entity); }
    
        // used by canDeactive route guard
    
        canDeactivate() {
            if (!this.hasChanged()) {
                return true;
            }
            return this.showConfirmationDialog().then(choice => {
                return choice !== ConfirmChoice.cancel;
            });
        }
    
        showConfirmationDialog() {
    
            return new Promise((resolve) => {
    
                this.confirmationDialog.show();
                . . .
    
                this.save().then(() => {
                . . .
    
                }, (err) => {
                    this.logError(err); // Implemented in base parent component
                });
    
            });
    
        }
    
        save() {
    
            // Value of dataService set in the child to support different APIs
            // Optionally override saveEntity in the child
    
            return this.updateService.update(this.dataService, this.saveEntity).then( . . .
    
       }
    
        protected get saveEntity() { return this.entity; }
    
        // Use in child HTML template to limit functionality
        get editAllowed() { // updatePermission could be overridden in the child
            return this.authorizationService.hasPermission(this.updatePermission);
        }
    
    }              



Build a specific form child component

child.component.ts


    @Component({. . .})

    export class ChildComponent extends BaseFormComponent {
    
        updatePermission = 'CHILD_UPDATE'; // can override the default permission
    
        protected routeParamName = 'child'; // required by parent to read route data
    
        constructor(private childDataService: ChildDataService) {
    
            super();
    
        }
    
        protected get dataService() { return this.childDataService; }
    
        protected get saveEntity() {
    
            // perhaps do some custom manipulation of data before saving
    
            return localVersionOfEntity;
    
        }
    
        protected additionalFormInitialize() {
    
            // Add custom validation to fields or other unique actions
    
        }
    
        hasChanged() {
    
            // Could override this method to implement comparison in another way 
    
        }
    
    }                 

As you proceed with your development, if you find yourself copying and pasting code, take a moment to see if some refactoring might be in order. Class inheritance can give you an opportunity to delete some code and that always feels good. Doesn’t it?

Share the post

Angular How-to: Simplify Components with TypeScript Inheritance

×

Subscribe to Msdn Blogs | Get The Latest Information, Insights, Announcements, And News From Microsoft Experts And Developers In The Msdn Blogs.

Get updates delivered right to your inbox!

Thank you for your subscription

×