This tutorial on Angular 8 components is in continuation of our Angular 8 Tutorial Series and if you have not read the previous parts of the tutorial , it is recommended that you go through them first. In the last part , we learned about many important files and folders in Angular 8 and we'll refer to them again and again in this and further parts.
Components are the cells or building blocks of an Angular app and when you're writing an Angular 8 app , you'll spend a significant time creating and modifying components. Technically components are Typescript classes along with a component decorator where we provide metadata that dictates how the component should be used by the app. Note that in order to be usable in an Angular 8 app , a component has to belong to a NgModule
. In this part of the tutorial , we'll go back to our app.component.ts
and explore its different parts and we'll also edit the component and add Inventions related information to the component. Let's get started.
Following is the code from our app.component.ts
file , read the informative comments to see what's happening in each line.
// app.component.ts
import { Component } from '@angular/core'; // import Component class from angular core
// define the component metadata usnig the decorator and export the class so it can be
// imported by other modules
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
}
import { Component } from '@angular/core';
// add a new class
export class Invention {
name : String ;
inventor : String ;
year : String;
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
// title = 'app';
invention : Invention = {
name : ' C Programming Language ' ,
inventor : ' Dennis Ritchie ' ,
year : ' 1972 '
}
}
app.component.html
to bind this object to the view. Open the file app.component.html
and make it look like the following snippet:
<!-- app.component.html -->
<div style="text-align:center">
<h1>
Welcome to {{title}}!!
</h1>
</div>
<h2> Greatest Inventions in History of Mankind </h2>
<hr>
<!-- bind data using curly braces to the data in app.component.ts -->
<h2> {{ invention.name }} </h2>
<h3> {{ invention.inventor }} </h3>
<h3> {{ invention.year }} </h3>
use command ng serve
to run your app and it starts your app on http://localhost:4200 as shown below:
> ng serve
ng serve
, It will automatically reload your changes in the browser , you don't have to restart your project or reload your browser.
Wow! we've done it again, so in this part of our Angular 8 tutorial , we started exploring angular components. we also looked at a very basic example of data binding. In the next part of the tutorial , we'll learn how to create components. Hope you are enjoying learning about the Angular 8 , see you in the next part.