Home » Framework » Angular » Create class interface enum service in angular application

Create class interface enum service in angular application

This article explains how to create a class, interface, enum, and service and usage of all in Angular Application.

First, let us create the new angular project to see all the examples.

ng new angular-first

The above command creates the new project named angular-first at the location you chose. At the time of project creation, it asks two questions like whether you need routing for this project? and which type of style format do you use?.

Here we do not deal with routing so you have to type 'n' for routing and for the type of style format you have to choose CSS. Now let us create the component to see the examples of class, interface, enum, and service.

ng g c first-component

The above command creates the component named first-component under the app folder. In this component, we have to see all the examples.

Now open the app.component.html file and replace it with the below code.

<app-first-component></app-first-component>

Run the project using the command ng serve. Then go to this URL http://localhost:4200 in the browser to see the view of your first-component with the message like "first-component works!".

We have created the new angular project successfully with one component. If you are not familiar with CLI commands and create a new angular project then please take a look at this Setup Angular Environment to create a new angular application and CLI commands of Angular.

Now let us see the examples of class, interface, enum, and service with this project.

Create Class in Angular Application

A class is a template is used to create an object with its properties like data types (or) member variables and methods. We can say it is an object constructor or blueprint for creating an object.

Let us create a class using the below command

ng g class profile (or) ng g cl profile

It creates the class under the app folder named Profile. There are two files created under the app folder that are spec and ts files.

Let's open the profile.ts file under the app folder and replace it with the below code.

export class Profile {    
    firstName:string="";
    lastName:string="";
    age:number=0;
    constructor(firstName:string, lastName:string, age:number){
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }
    getName(){
        return this.firstName + " " + this.lastName;
    }
}

In the above class, we have declared the properties firstName, lastName, and age and the constructor to create an instance of the class and the getName() function to return the full name.

Now let us use this class in the component. Open the first-component.component.ts file and replace it with the below code.

import { Component, OnInit } from '@angular/core';
import { Profile } from '../profile';
@Component({
  selector: 'app-first-component',
  templateUrl: './first-component.component.html',
  styleUrls: ['./first-component.component.css']
})
export class FirstComponentComponent implements OnInit {
  fullName:string='';
  profile:Profile = new Profile("Salman","khan",30);   
  constructor() {    
  }
  ngOnInit(): void {    
    //create single class object    
    this.fullName = this.profile.getName();
  }
}

In the above code,

  1. We created one instance (or) object for the Profile class with values.
  2. Declared the string 'fullName' to get the full name from the Profile object.
  3. The method fetched the Full Name from the created Profile object and assigns it to the string 'fullName'.

Let us see the result by putting the below code in the first-component.component.html file.

<p>Example of Class</p>
<div>
    <table>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Age</th>
        <tbody>
            <tr >
                <td>{{profile.firstName}}</td>
                <td>{{profile.lastName}}</td>
                <td>{{profile.age}}</td>
            </tr>
        </tbody>
    </table> 
</div>
<div>
    {{fullName}} - Full Name fetched using getName() method.
</div>

Run the application again by using the ng serve command. You can see the result below in the browser.

Angular-Class-Example
Angular-Class-Example

Let see the code in the class file (profile.ts). In that, we have declared the member variables first and set the values of that within the constructor while creating the instance. But we can create the class without declaring the properties also. Yes, the other way of writing class is below.

export class Profile {    
    constructor(
        public firstName:string,
        public lastName:string,
        public age:number
    ){}
    getName(){
        return this.firstName + " " + this.lastName;
    }
}

Both the formats of writing class produce the same result. Now let us create the multiple class objects and show the result in the component's view template.

Let's do the changes below in the first-component.component.ts file

  1. Declare the array of type Profile class at the top like below.

profileList:Profile[] = [];

2. Create multiple objects for the Profile class and put that in the array we declared above. Add the below code within ngOnInit() function.

this.profileList = [
      new Profile("John", "peter", 30),
      new Profile("Salman", "khan", 30),
      new Profile("Sachin", "Tendulkar", 30)
];  

Finally, the code of the first-component.component.ts file is like below.

import { Component, OnInit } from '@angular/core';
import { Profile } from '../profile';
@Component({
  selector: 'app-first-component',
  templateUrl: './first-component.component.html',
  styleUrls: ['./first-component.component.css']
})
export class FirstComponentComponent implements OnInit {
  fullName:string='';
  profile:Profile = new Profile("Salman","khan",30);
  profileList:Profile[] = [];  
  constructor() {}
  ngOnInit(): void {    
    //create single class object    
    this.fullName = this.profile.getName();
    //Array of Class Objects
    this.profileList = [
      new Profile("John", "peter", 30),
      new Profile("Salman", "khan", 30),
      new Profile("Sachin", "Tendulkar", 30)
    ];  
  }
}

To show this class of objects in the component's template then add the below code in the first-component.component.html file.

<p>Iterate Array of Class Objects</p>
<table>
    <th>First Name</th>
    <th>Last Name</th>
    <th>Age</th>
    <tbody>
        <tr *ngFor=" let prof of profileList">
            <td>{{prof.firstName}}</td>
            <td>{{prof.lastName}}</td>
            <td>{{prof.age}}</td>
        </tr>
    </tbody>
</table>

Save all the changes and run the application again. You can see the list of objects in the browser.

Access modifiers of the properties of a class

There are 3 types of access modifiers available for the class properties that are private, public, and protected.

Public - We can access the properties of the class throughout the application. By default, the member variables are public if there is no modifier declared.

Private - We can access the properties within the member functions of the same class.

Protected - We can access the properties within the class and any class that inherits.

Now let's change the properties of the Profile class with the access modifier private like below.

export class Profile {    
    constructor(
        private firstName:string,
        private lastName:string,
        private age:number
    ){}
    getName(){
        return this.firstName + " " + this.lastName;
    }
}

Save the changes and run the application again. Now you can see the error message like properties of Profile class are private and only accessible within the Profile class.

Cool!. For fixing this we have to make the properties with the modifier public (or) we have to change the type of declared variables from Profile to any like below in the first-component.component.ts file.

From

profile:Profile = new Profile("Salman","khan",30);

To

profile:any= new Profile("Salman","khan",30);

From

profileList:Profile[]=[];

To

profileList:any=[];

Once you changed the type with any then save the changes and run the application again. You can see the result in the browser without any issue.

Interface and Enum in Angular Application

The interface is a structure that only defines the properties and methods. Let us create the interface in our project by using the below command.

ng g i computer

The above command creates the interface named Computer under the app folder. Let's open the file computer.ts and define some of the properties like below.

export interface Computer {
    brand:string;
    ram:string;
    type:string;
    version:number;
}

Now let us use this interface in the component. Replace the below code in the first-component.component.ts file.

import { Component, OnInit } from '@angular/core';
import { Computer } from '../computer';
@Component({
  selector: 'app-first-component',
  templateUrl: './first-component.component.html',
  styleUrls: ['./first-component.component.css']
})
export class FirstComponentComponent implements OnInit {
  computer:Computer[]=[];  
  constructor() { }

  ngOnInit(): void {   
    //Interface
    this.computer =[
      {"brand":"Dell", "ram":"12 GB", "type":"Desktop", version:2.0},
      {"brand":"HP", "ram":"12 GB", "type":"Desktop", version:1.0},
      {"brand":"ASUS", "ram":"16 GB", "type":"Laptop", version:4.0}
    ];
  }
}

Replace the below code in the first-component.component.html file.

<p>Example of Interface</p>
<table>
    <th>Brand</th>
    <th>Ram</th>
    <th>Type</th>
    <th>Version</th>
    <tbody>
        <tr *ngFor=" let com of computer">
            <td>{{com.brand}}</td>
            <td>{{com.ram}}</td>
            <td>{{com.type}}</td>
            <td>{{com.version}}</td>
        </tr>
    </tbody>    
</table>

Save all the changes and run the application again to see the below result in the browser.

Angular-Interface-Example
Angular-Interface-Example

Create Enum in Angular

Enums are a feature to define a set of named constants in an angular application. Let create the enum by using the below command in our application.

ng g enum ComputerType

Open the file computer-type.ts file and define some constants like below.

export enum ComputerType {
    Desktop = 'Desktop',
    Laptop = 'Laptop',
    Palmtop = 'Palmtop',
}

Let's use this enum in the component. Replace the below code in the first-component.component.ts file.

import { Component, OnInit } from '@angular/core';
import { Computer } from '../computer';
import { ComputerType } from '../computer-type';
@Component({
  selector: 'app-first-component',
  templateUrl: './first-component.component.html',
  styleUrls: ['./first-component.component.css']
})
export class FirstComponentComponent implements OnInit {
  computer:Computer[]=[];
  computerList:Computer[]=[];
  computerTypes: Array<string> = Object.keys(ComputerType).filter(key => isNaN(+key));
  
  constructor() {}

  ngOnInit(): void {     
    //Interface
    this.computer =[
      {"brand":"Dell", "ram":"12 GB", "type":"Desktop", version:2.0},
      {"brand":"HP", "ram":"12 GB", "type":"Desktop", version:1.0},
      {"brand":"ASUS", "ram":"16 GB", "type":"Laptop", version:4.0}
    ];
    
    //Interface using Enum
    this.computerList =[
      {"brand":"Dell", "ram":"12 GB", "type":ComputerType.Desktop, version:2.0},
      {"brand":"HP", "ram":"12 GB", "type":ComputerType.Laptop, version:1.0},
      {"brand":"ASUS", "ram":"16 GB", "type":ComputerType.Palmtop, version:4.0}
    ];
  }
}

Replace the below code in the first-component.component.html file.

<p>Example of Interface</p>
<table>
    <th>Brand</th>
    <th>Ram</th>
    <th>Type</th>
    <th>Version</th>
    <tbody>
        <tr *ngFor=" let com of computer">
            <td>{{com.brand}}</td>
            <td>{{com.ram}}</td>
            <td>{{com.type}}</td>
            <td>{{com.version}}</td>
        </tr>
    </tbody>    
</table>
<p>Example of Enum</p>
<table>
    <th>Brand</th>
    <th>Ram</th>
    <th>Type</th>
    <th>Version</th>
    <tbody>
        <tr *ngFor=" let com of computer">
            <td>{{com.brand}}</td>
            <td>{{com.ram}}</td>
            <td>{{com.type}}</td>
            <td>{{com.version}}</td>
        </tr>
    </tbody>    
</table>
<p>Convert Enum into array of String</p>
<div>{{computerTypes}}</div>

We can convert the enum values into an array of strings. The below code does that.

computerTypes: Array<string> = Object.keys(ComputerType).filter(key => isNaN(+key));

Now save all the changes and run the application again to see the below result in the browser.

Angular-Enum-Example
Angular-Enum-Example

Create services in Angular Application

If we want to write some common task that we can use anywhere from the entire application then use services to achieve that. The common tasks include business logic, processing data for the components and etc.

Here let us create a service named ProfileService by using the below command.

ng g service profile

The above command creates the two files under the app folder that are profile.service.ts and profile.service.spec.ts. Now we open the profile.service.ts file and replace it with the below code.

import { Injectable } from '@angular/core';
import { Profile } from './profile';

@Injectable({
  providedIn: 'root'
})
export class ProfileService {
  profile:Profile[]=[];
  constructor() { }
  public getProfiles(){
    this.profile = [
      new Profile("John", "peter", 30),
      new Profile("Salman", "khan", 30),
      new Profile("Sachin", "Tendulkar", 30)
    ];
    return this.profile
  }  
}

In the above code, we have declared the method getProfiles() to return the list of Profile data. We can call this method from any component in the application to get the list of Profile data.

The @Injectable() decorator specifies that we can inject this service in any component through the dependency injection system. The metadata providedIn: 'root' describes that the service is available throughout the application.

Now we can Import and inject the ProfileService in the first-component.component.ts file like below

import { ProfileService } from '../profile.service';
constructor(private profileSevice:ProfileService)

Replace the below code in the first-component.component.ts file.

import { Component, OnInit } from '@angular/core';
import { Profile } from '../profile';
import { ProfileService } from '../profile.service';
@Component({
  selector: 'app-first-component',
  templateUrl: './first-component.component.html',
  styleUrls: ['./first-component.component.css']
})
export class FirstComponentComponent implements OnInit { 
  profileList:Profile[]=[];  
  constructor(private profileSevice:ProfileService) {    
  }
  ngOnInit(): void {    
    //data fetched from ProfileService
    this.profileList = this.profileSevice.getProfiles(); 
  }
}

Open the first-component.component.html file and replace it with the below code

<p>Example of Sevice (Fetched the Profile data through Service)</p>
<table>
    <th>First Name</th>
    <th>Last Name</th>
    <th>Age</th>
    <tbody>
        <tr *ngFor=" let prof of profileList">
            <td>{{prof.firstName}}</td>
            <td>{{prof.lastName}}</td>
            <td>{{prof.age}}</td>
        </tr>
    </tbody>
</table>

Now save all the changes and run the application again to see the result in the browser.

I hope you understood how to use class, interface, enum, and service in angular application. Thanks!. Keep Reading!.

Download the source code with all the examples of class, interface, enum, and service from GitHub.

Leave a Reply

Your email address will not be published. Required fields are marked *