Create a Component in Angular 4

Angular Tutorial

In this article are will learn how to create a component, how to create a component within a component and how to use the component in angular 4 Application.

The Angular CLI has something that we call generators that let you generate components, routes, services and pipes with a simple command in the application for you. For instance, you can use the following command to create a component

How to create a component in Angular 4?

ng generate component header

here ng generate is a command through which we are generating a component named header.

if you want to create a component within a folder then you can create using below-mentioned command

ng generate component components/header

There is also a shorthand version of the above command.

ng g c components/header

both command will act as a same.

here ng generate will create a component header within a components folder. Here “components” folder is not necessary but it is good to put the related components in a folder. So that you will have a nice project structure.

angular4 component

 

This is the expected output you will get when you run the above command.

Now how to use the component which we have just created.

Now you can put HTML related code in header.component.html file and the logic part will be in header.component.ts and if you have CSS related that component only you can put in header.component.css.

So we have created a component called header. Now we will create a component called footer and will put it in the same folder called components.

ng g c components/footer

To run you angular app run the command ng serve. Open your browser and run http://localhost:4200/.

angular default page

Now, let’s use our created component in our application.

So open app.module.ts. Now you can see header and footer component files are already declared in app.module.ts as you can see below:-

import { BrowserModule } from ‘@angular/platform-browser’;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { NgModule } from '@angular/core';
 
import { AppComponent } from './app.component';
import { HeaderComponent } from './components/header/header.component';
import { FooterComponent } from './components/footer/footer.component';
 
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
FooterComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Now open src\app\app.component.html. And add <app-header></app-header> and <app-footer></app-footer>

So to add component in view file you need to put app- before component name. try to make you index page like the image as below:

 

header-footer component