Angular components allow us to define both the logic and the views for our app. A component is basically structured in three different sections:

Understanding Angular Components And How They Work 1

  1. Imports

    Imports reside at the top of the file and allows us to use a variety of libraries that our component may consume.

  2. Component Decorator

    The component decorators are basically metadata that lets the Angular application know how to process our class. Information regarding which HTML views and CSS are defined here.

  3. Component Class

    The component class defines the logic which will be specific to our components.

If we take a look at the app.component.ts file which was created in the previous post, we can see that the content appears as below:

Sections Of Angular Components
Sections Of Angular Components

Sections Of Angular Components In Depth

On the first line, we have our Imports. Right now, there is only one required import and we can have multiple imports as we develop our component. From the third line, we have our Component Decorator with the associated metadata. Finally, on line eight, we have the Component Class.

Within the Component Decorator, we have three properties and their values defined as:

selector: 'app-root',


styleUrls: ['./app.component.css']
If we take a look at the “index.html” file, we can see that the the “selector” is designated within the body of the file as:

This is where the app.component.ts view will be loaded. The html that gets loaded here is defined in the “templateUrl” which is “app.component.html“. Also, the CSS styles for this template are defined in the “styleUrls” which is “app.component.css” file.

Finally, another important thing to note here is that the value of the “title” property which is defined inside the AppComponent class is used in the “templateUrl” using Interpolation.

So as you can see, we can easily make reference to the objects created in the Component class inside our views.
This, in a nutshell, is how the Component works in Angular.