Angular 2 – Components

Angular 2 Components

What is component in angular 2?

As the name implies a component is basically a typescript class with HTML template, that is used to show an element on the browser screen. Every components has some properties and by using them we can manipulate how the element should look  and behave on the screen. We can manage interaction using this properties.


Create Your First Components using Angular CLI:

When you have completed the project Setup, just type the command. This is the shortest way to generate a component using Angular CLI.

Now here is your user-list.component.ts file

Angular 2 Metadata

In Decorator Function we define the metadata for our component. The objective of these decorators functions is to allow us to add meta-data information of component, that will tell Angular 2 how to process a class.

When creating any Angular components, we are able to configure the following metadata options an components:

Component consists of the following Parts:

1. selector:

Selector defines the name of the HTML tag where this component will render. In this case, our component will by shown using the <app-user-list></app-user-list> tag in HTML.

2. template or templateUrl :

This is the view section of our component that holds our template. Template can consists of HTML TAGs and other component as well. It allows us to tie logic from our component directly to a view. When defining a template, we can either write it inline template , or we can also use templateUrl to link to an external template.

We personally recommended you to use external template to keep you code simple and maintanabe.

3. styles  or stylesUrls :

The styles option is used to apply CSS on this component. We could have just as easily linked to an external stylesheet by using the styleUrls property separated by commas.


Now add  <app-user-list></app-user-list>  tag in to  any other component or in root component, where you want to display this component.