How to create a component in angular

In this tutorial we will understand how to create a component in angular application. We have already seen what is an angular component though, but we will look into it again. In Angular each functionality can be made as a component which can be used in the entire application just by importing it. So now we will look into the steps to create a component in angular.

Let’s Begin ! – Just 2 Steps

Step 1 :

create a new directory inside app directory for better management of components(not mandatory)

> mkdir contact

Step 2 :

Now, create component by using command as below

> ng g c contact –flat

-g : to generate

-c : for component

–flat in an option used to stop create a directory of same name as the name given in the above command, and create all files in the current directory. It puts the file in src/app instead of its own folder.

So the above command creates 4 files as shown below in this snapshot.

create-angular-component-using-angular-cli

This creates 4 files :

contact.component.html file : file write the html content of your page exists.

contact.component.spec.ts : file where you have the test cases

contact.component.ts : file where you write the functionality and logics in this typescript.

contact.component.css : file where you write the css content of the page.

 Next, Include this component in main app.component.html 

by including the tag in app.component.html as per the selector created in contact.component.ts

<app-contact></app-contact>
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-contact',
  templateUrl: './contact.component.html',
  styleUrls: ['./contact.component.css']
})
export class ContactComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }
}

Summary

In this tutorial, we learnt how to create a component in angular application and add the created component using its html selector tag to any other component like AppComponent here. Enjoy learning Angular.
Hope you liked it!


Leave a Comment