Simple Component in Angular 2


Component

Components are the most basic building block of an UI in an Angular application. It is nothing but an angular 2 class with some properties and methods.

Prerequisites

Angular Cli must be installed if not installed check out my previous article “Install and run Angular 2 apps using Angular CLI”. Some basic knowledge on Html, Css, Javascript, Oops.

Create a new component

Using command :

ng generate component books

it will automatically generate default files, code related and configure books component in app.module file.

Manually :

create a folder inside “/src/app/” with component name(books — example component)

Inside books folder create an new typescript file, html file, css file with name as given below.

books.component.ts
books.component.html
books.component.css

finally folder structure will be “/src/app/books/”.

books.component.ts

It is our core file for a component and other two files (books.component.html, books.component.css) optional.

Note :

if your template and styles has more lines of code, it is recommended to go with separate files for easy maintenance and readability.

books.component.ts without separate html and css files :

Books component type script file

books.component.ts with separate html and css files :

books.component.html

books.component.css

since we created books component manually, it needs to be added in our module file to expose this component to outside world connected with that module.

In our example we are going to add it in app.module.ts file.

import our component

import { AppComponent } from ‘./app.component’;
import { BooksComponent } from ‘./books/books.component’;

Add our component to declarations.

@NgModule({
 declarations: [
 AppComponent,
 BooksComponent
 ],
 bootstrap: [AppComponent]
 })
export class AppModule { }

app component will be created while installing angular cli which is loaded while app bootstrapped.

Analyzing books.component.ts

import { Component } from ‘@angular/core’;

Imported the component decorator from Angular core module.

@Component({
 selector: ‘app-books’,
 templateUrl: ‘./books.component.html’,
 styleUrls: [‘./books.component.css’]
 })

Included component decorator and added selector, template and styles inside that decorator

export class BooksComponent {}

Final step : exported class to make sure it can used further”

Example : if books component is used in app component will be like below.

Thank you!!! Happy Coding.