How to use composition instead of inheritance when sharing logic between components in Angular 6?

For composing objects in angular you need to have a reference to that object inside of your class, which shares data and functionality. To do that you need to use Angular services, and inject them to your class, and there should be 1 instance of service per component.

  1. Create a new service by running ng g s my-service, remove providedIn: 'root' from your service annotation (We want to provide instance per component)
  2. Add public available: boolean = true; to the service
  3. provide the service through the components, in @Component configs on your components
  4. inject the service in your both component constructors, constructor(private myService:MyService)

Now you have a composition that keeps data and functionality


If you create same components with big part same logic. you can use inheritance for example controlSelectComponent and controlInputComponent stackblitz example

For composition you need to create service and provide it to both components. But you dont keep component state in service becose all service are singletone. And when one component change state another component crash.

You also can provide service to each component in providers section

@Component({
  selector: 'app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [MyService]
})
export class AppComponent {
  constructor(private myService: MyService) {
  }
}

But in case with saving state in service is not the best solution

Conclusion

Use services and composition for share helper methods between components.

Use abstract class and inheritance for components with same logic and state changes.