Understanding the AppComponent


Go ahead and open the src/app/app.component.ts file and let’s understand the code behind the main/root component of the application.

First, this is the code:

import { Component } from  '@angular/core';
    selector:  'app-root',
    templateUrl:  './app.component.html',
    styleUrls: ['./app.component.css']
export  class  AppComponent {
    title  =  'app';

We first import the Component decorator from @angular/core then we use it to decorate the TypeScript class AppComponent. The Component decorator takes an object with many parameters such as:

  • selector: specifies the tag that can be used to call this component in HTML templates just like the standard HTML tags
  • templateUrl: indicates the path of the HTML template that will be used to display this component (you can also use the template parameter to include the template inline as a string)
  • styleUrls: specifies an array of URLs for CSS style-sheets for the component

The export keyword is used to export the component so that it can be imported from other components and modules in the application.

The title variable is a member variable that holds the string ‘app’. There is nothing special about this variable and it’s not a part of the canonical definition of an Angular component.

Now let’s see the corresponding template for this component. If you open src/app/app.component.html this is what you’ll find:

<div  style="text-align:center">
Welcome to !
    <img  width="300"  alt="Angular Logo"  src="data:image/svg+xml;....">

    <h2>Here are some links to help you start: </h2>
    <h2><a  target="_blank"  rel="noopener"  href="https://angular.io/tutorial">
Tour of Heroes</a></h2>
    <h2><a  target="_blank"  rel="noopener"  href="https://github.com/angular/angular-cli/wiki">
CLI Documentation</a></h2>
    <h2><a  target="_blank"  rel="noopener"  href="https://blog.angular.io/">
Angular blog</a></h2>

The template is a normal HTML file (almost all HTML tags are valid to be used inside Angular templates except for some tags such as <script><html> and <body> etc.) with the exception that it can contain template variables (in this case the title variable) or expressions ({{...}}) that can be used to insert values in the DOM dynamically. This is called interpolation or data binding. You can find more information about templates from the docs.

You can also use other components directly inside Angular templates (via the selector property) just like normal HTML.

If you are familiar with the MVC (Model View Controller) pattern, the component class plays the role of the Controller and the HTML template plays the role of the View.


Please enter your comment!
Please enter your name here