Angular Components - Basics and Structure

Jun 30 2022

2 min read


#Structure of a Component

Every component in Angular is made up of two main parts:

  • The @Component decorator
  • The actual component class

The following example shows how a component is structured.

import { Component } from '@angular/core'
selector: 'app-root',
templateUrl: './app-component.html',
styleUrls: ['./app-component.scss']
export class AppComponent {
title: 'App';
count: 0;
constructor() {}
setCount() {
this.counter += 1;

The @Component decorator has 3 main parts:

  • selector: The HTML tag of the component that is used in other components. The tag will be used as <app-root></app-root>.
  • templateUrl: The path where the components HTML file is located which will act as view.
  • styleUrls: Array of CSS files used by the component.

#Component Class

Below the @Component decorator, we have the class where all the logic is written. The component class consists of all the objects which we can bind to the template and methods which can be called from the template as event bindings.

<p>{{ title }}</p>
<button (click)="setCount()" >Counter: {{ count }}</button>

#Interpolation and One-Way Data binding

#What is Interpolation?

Interpolation, or string interpolation, is where you see the text within the {{}} brackets, telling Angulat to interpret the text within the brackets and use one-way data binding to replace the text with the value of the property of the same name defined in the component class.

#What is One-Way Data Binding?

One-Way data binding is where you have a property in your component class, and when the value of that property is updated, this value is passed to the view.

In the above code snippet, we can see string interpolation where title and count variables are wrapped inside {{}} brackets which will resolve into actual values when the view is loaded or updated.

Angular can also read JavaScript within these brackets and return the result value to the view.

<p>{{ 10 + 20 }}</p>

When Angular sees such expression, it knows what kind of operation should be performed to evaluate the result. In this case it will add both numbers and return 30.