Skip to content

Angular / Component and Services


Creating a Component

Components are the most basic building blocks of an Angular application. An Angular application contains a tree of Angular components.

Angular components are a subset of directives, always associated with a template. Components can be thought of as the controller in the MVC structure. Unlike other directives, only one component can be instantiated per element in a template.

A component must belong to an NgModule (e.g. app.modules.ts) in order for it to be available to another component or application. To make it a member of an NgModule, list it in the declarations field of the NgModule metadata. This is taken care of automatically when using the Angular CLI to generate a component.

Note that, in addition to these options for configuring a directive, a component's runtime behavior is controlled by implementing life cycle hooks. For more information, see the Lifecycle Hooks guide.

Use the Angular CLI to automatically generate a component and all the files associated with it, as well as automatically include it in the NgModule, app.modules.ts. See below for an example of how to create a component named "my-component".

Example:

ng generate component my-component

Creating a service

Using the Angular CLI, create a service called hero.

ng generate service hero

Why Services?

Components shouldn't fetch or save data directly and they certainly shouldn't knowingly present face data. They should focus on presenting data and delegate access to a service.

Services are a great way to share information among classes that don't know each other.

See the Angular Documentation for more information on services.