Marcos J.C Kichel
Marcos J.C Kichel

Reputation: 7219

Is it possible to create a Component abstraction on Angular 2?

I want to create a AbstractComponent with initial behavior while being able to override it on child when needed, is it possible? Is it a good practice?

Should look more or less like that:

export abstract class AbstractComponent implements OnInit {

  constructor(authService: AuthService, router: Router) {}

  ngOnInit() {
    if (authService.userNotLoggedInAnymore()) {
      router.navigate(['Login']);
    }
  }

  ...
}

Upvotes: 14

Views: 16209

Answers (3)

Kiang
Kiang

Reputation: 31

This might be a little late but I found a workaround for those who are getting

ERROR in Cannot determine the module for class [MyComponent] in [file]!
Add [MyComponent] to the NgModule to fix it.

when building with AOT. When adding the component to the declaration section, try cast it with <any> e.g. <any>MyComponent. This doesn't sound so clean but at least it works for me. If anyone happens to find a better solution, please kindly share :)

Upvotes: 2

Mike
Mike

Reputation: 166

As an alternative you can also do without the constructor parameters in the abstract class at all and declare the services with the @Inject decorator, then you don´t need to touch the constructor of the inheriting class and call the super(...)-method there:

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

export abstract class AbstractComponent implements OnInit {

  @Inject(AuthService) private authService: AuthService;
  @Inject(Router) private router: Router;

  ngOnInit() {
    if (authService.userNotLoggedInAnymore()) {
      router.navigate(['Login']);
    }
  }
  ...
}

Upvotes: 4

Langley
Langley

Reputation: 5344

Yes, just extend that class with the real @Component and call super() in the methods you override, like ngOnInit. And you also have to override the constructor with at least the same or more dependencies in the parent and pass them with super() too.

Upvotes: 13

Related Questions