Angular - Component Overview

Angular - Component Overview

Welcome to the Series

Welcome to the Angular App Development series, where we will learn the ingredients of Angular and the step by step processing of creating an Angular App - through the motto learning by doing.

Till now..

The readers are expected to have some working knowledge on the Web Application using HTML, Javascript, CSS and optionally a Web Application Framework in any of the popular Programming Languages like Java, Dot Net, PHP etc., Even otherwise, it should be fine. Welcome aboard! :)

In this post...

When you generate a new application in Angular via

ng new my-app

we get the application code generated by Angular with the main component named 'app' inside the 'src' folder. The typical app.component.ts file looks like below

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'todo';
}

It is typical to the MVC architecture where we have the main Controller is replaced by the component and the View is driven by the combination of HTML and CSS (they are indeed separated further). The Model is the .ts file itself (main source code the component.ts file) which can have the attributes that can be bound in the HTML file through the property binding with the {{...}} braces. It is called as interpolation where the model attribute values are referred and reflected in the template.

The individual attributes are mentioned in the @Component declaration inside the component.ts file with the 3 different keys - selector, templateUrl, styleUrls.

  • selector => This selector is the element tag name to be used in the HTML files, like <app-root></app-root> in the index.html file to include the output of this component in the HTML file.
  • templateUrl => The templateUrl contain the .html file to be picked up when the view is supposed to be prepared by the component
  • styleUrls ==> This attribute contains the list of .css files to be applied to beautify the HTML content.

They are the plain old HTML and CSS files and they are now declared in the .ts file under the @Component section for the better organized way of development.

The Component is a decorator that is imported from the '@angular/core' package in the .ts file to be used further