Angular jsJavaScript

How to Use Interface in Angular?

In this tutorial, we will learn how to use the interface in an angular component. you can understand the concept of angular interface example. you’ll learn how to use interface in angular. We will use an angular export interface example.

I will simply explain what is an interface in angular and why we have use interface in angular component. you can easily use interface in angular 6, angular 7, angular 8 and angular 9 application.

Let’s see bellow explanation and instruction about interface in angular app.

What is Interface in Angular?

Interface is a specification that identifies a related set of properties and methods to be implemented by a class. So basically using interface you can set some basic rules for your properties and methods using class.

Sometimes we are creating object array with specific datatype field like id has to be integer or number, the name has to be a string value, the birth of date has date datatype data. but sometime we might have a mistake and set string value instead of integer or number then it caught the problem and your app will show you an error. But if you use interface then it will solve the problem when you write code on your IDE. IDE will show you error quirky where it is a problem.

How to Define Interface in Angular?

Here, I will show you a very simple example of how to define interface class in angular. you can see bellow code for defining an interface.

export interface Student {

    id: number;

    name: string;

}

export:The export keyword will help to use import this class on other component and class.

interface:The interface ia a keyword so using this keyword you can set interface.

Student: Student is a class name that describe interface details.

Now let’s see two example as bellow:

How to Use Interface in Angular Component?

src/app/app.component.ts

import { Component } from '@angular/core';
  
interface Student {
    id: number;
    name: string;
}
  
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
    
  students: Student[] = [
    {id: 1, name: "Hardik"},
    {id: 2, name: "Paresh"},
    {id: 3, name: "Rakesh"},
  ]
}

Angular Export Interface Class Example

src/app/student.ts

export interface Student {
    id: number;
    name: string;
}
src/app/app.component.ts
import { Component } from '@angular/core';
import { Student } from './student';
  
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
    
  students: Student[] = [
    {id: 1, name: "Hardik"},
    {id: 2, name: "Paresh"},
    {id: 3, name: "Rakesh"},
  ]
}

I hope it can help you…

Related Articles

Leave a Reply

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

Back to top button