0

Suppose we have these routes:

/products -> ProductsController (show all products)

/products/cat/:catid -> CatsController (show products in specific cat)

/products/tag/:tagid -> TagsController (show products with specific tag)

These components have a lot of shared functionalities (all of them show list of products), but there is some small changes. For example i want to show <h1>CategoryName</h1> at CatsController.

I want the components to be separate , but i don't want duplicate codes. I think i need some kind of component inheritance here (cat and tag inherite from products), but not sure how i can achieve this in angular.

Whats the best practice to achieve this?

2 Answers 2

1

Angular and most other Web-Development frameworks prefers Composition/Aggregation over Inheritance in terms of Object-Oriented Paradigm.

Approach 1: I suggest to design ProductsController in such a way that it can accept data as inputs and embed the this ProductsController in CatsController.

<app-cats>
<h1>CategoryName</h1>
<app-products [data]="data" (onSelect)="HandleSelection"></app-products>
</app-cats>

Approach 2: Extract all your common business logic to separate Service. Inject that service in ProductsController, CatsController and TagsController to use common functionality. In short, let the components be presentational components only and move business logic to separate utility or service classes.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use extends on the class...

export class TagComponent extends BaseComponent {
constructor(private myService: MyService) {
    super(myService);
}

Just make sure to call the base's constructor with super() if needed...

But for shared functionality between components, depending on your needs, it may be best to use a Service, or if the changes are more display-oriented on the objects being rendered, a Directive each view can use might be your best best.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.