Angular Component and Overview

Kailash Chandra Behera | Saturday, November 18, 2023

In my previous two posts, we learned setting up angular development environments and create first hello work angular project using angular CLI. Here we will explore the angular component and their associated elements. Also, we will demonstrate to create a new component in angular using CLI and Visual Studio Code editor.

Getting Started

Components in angular are the basic building blocks, a component of angular consists a component decorator, which includes properties that allow you to define the template, CSS styling, animations, etc.. and a class, which is where your component logic is stored. Angular components reside within the /src/app folder. app.component.ts is one of the angular component example.

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

Angular Component Example

There are three angular elements inside the component decorated those are:

  • Selector: is a string value contains name of the component to identify the component in the DOM
  • Template URL: The template URL contains the path of angular user interface file, you can use template instead of template URL if your html page is simple for creating an user interface.
  • StyleUrls: contains reference of style file.
  • AppComponent: Is a class nothing but codes which support view and is created by TypeScript.

Angular Create New Component

There are mainly two ways to create or generate angular components that is using CLI and editor. Here we will demonstrate both the ways to create angular components.

Generate Angular Component using CLI.

The ng generate component angular CLI command is used to create a new component in angular.

Syntax
 ng generate component <component-name>  

Where component-name is the name of your new component.

Steps
  • Open the windows command prompt.
  • Navigate to your project folder.
  • Run the command: 'ng generate component <component-name>'
  • Then press Enter key

This CLI will create four files with component name that is .ts, .css, html and .spec.ts. for example, if you want to create a component with name login then ng component CLI command will create following four files.

  • login.compoment.ts
  • login.compoment.html
  • login.compoment.css
  • login.compoment.spec.ts

Go to your project folder then src/app, you will find a new folder with the name Login. Inside the folder you will find above mentioned folder.

Angular Create Component using Visual Studio Code Editor.

Visual Studio Code (VSCode) is the best editor for angular development. It is recommended to you use VSCode while working with angular projects. Follow the below steps to create a new angular component.

  1. Open the Visual Studio Code Editor.
  2. Open your project folder then expand the explorer.
  3. Then right click on the app folder and create a new folder.
  4. Give the name to the folder.
  5. Inside the newly created folder, create a new file with name test.component.ts
  6. Then open the component file and past the below code inside it.
     @Component({  
      selector: 'test-component',  
      template: '<h1>Hello World!</h1>',  
      styles: ['h1 { font-weight: normal; }']  
     })  
    
  7. Note that we have used template here instead of templateurl. If your angular ui components are big you can use the templateurl.
  8. If you are using templateurl then you must create another file with the name test.component.html which will contain your UI related logics.
  9. You may notice another thing here that we have not specified the styleUrls which indicates that this component will use the default style.
Demonstration

Here in this demonstration, we will continue the project mentioned in the previous blog post and will show list of students (Static List) in the newly added component.

Open the commpand prompt and navigate to your project folder. Run the below command on the command prompt to generate component in your project.

 ng generate component student  

Then in the VS code editor, open the project folder. You will notice a folder is added in the app folder with same name as your component.Also following four files will be inside the newly created folder.

  • student.compoment.ts
  • student.compoment.html
  • student.compoment.css
  • student.compoment.spec.ts

Inside the app folder, add a new folder with name Models then create a file studetn.ts inside the Models folder. This student.ts file is our model file to store student information. Copy below codes and past it inside the student file.

 export class student{  
      constructor(public FName:string, public LName:string){  
      }  
 }  

Open the component student.component.ts file, import the student model to component. the below code helps to import the student model, copy the code and paste it after import component code.

 import { Student } from "../Models/student";  

The placed code should look like.

 import { Component } from "@angular/core";  
 import { Student } from "../Models/student";  

Now go to the component class StudentComponent, copy the below codes are written to populate the model which data will be displayed in view and past it inside the class.

 Students:Array<Student>;  
 constructor(){   
      this.Students=new Array<Student>();  
      this.Students.push(new Student("Kailash","Behera"));  
      this.Students.push(new Student("Ramesh","Gouda"));  
      this.Students.push(new Student("Pancha","Gouda"));  
 }  

Your componet file content should look like below.

 import { Component } from "@angular/core";  
 import { Student } from "../Models/student";  
 @Component({  
   selector:'student',  
   templateUrl:'./student.component.html'  
 })  
 export class StudentComponent{  
      Students:Array<Student>;  
      constructor(){  
           this.Students=new Array<Student>();  
           this.Students.push(new Student("Kailash","Behera"));  
           this.Students.push(new Student("Sanjay","Sethi"));  
           this.Students.push(new Student("Pancha","Gouda"));  
      }  
 }  

We have added component and model into project successfully. now we will change in view. copy the below code and past it in the student.component.html file. your view code should look like below.

 <h1>Student List<h1>  
 <table border="1">  
      <tr>  
           <th>First Name</th>  
           <th>Last Name</th>  
      </tr>  
      <tr *ngFor="let item of Students">  
           <td>{{item.FName}}</td>  
           <td>{{item.LName}}</td>  
      </tr>  
 </table>  

Angular UI Components

We have done with all the activities to add a angular component to project. Our next step is to register our newly added component to projet. Open the app.module.ts file and add below code to import StudentComponent.

 import {StudentComponenet} from './student/student.compoment';  

In the declarations section, add StudentComponenet as follows

 @NgModule({  
  declarations: [  
   AppComponent, StudentComponenet  
  ],  
  imports: [  
   BrowserModule  
  ],  
  providers: [],  
  bootstrap: [AppComponent]  
 })  

your app.module.ts file content should look like as bellow

 import { BrowserModule } from '@angular/platform-browser';  
 import { NgModule } from '@angular/core';  
 import { AppComponent } from './app.component';  
 import { StudentComponenet } from './student/student.component';  
 @NgModule({  
  declarations: [  
   AppComponent, StudentComponenet  
  ],  
  imports: [  
   BrowserModule  
  ],  
  providers: [],  
  bootstrap: [AppComponent]  
 })  
 export class AppModule { }  

Finally open the app.component.html and use the StudentCompoment as follows

 <student></student>  

Summary

Here in this blog post, we learned to create component angular using CLI and editor(VSCode). I hope this post will be helpful.

Thanks


No comments: