Angular Interface Tutorial | Angular 9/8/7 Interface Example

April 28, 2020 | Category : Angular 9 Angular 8 Angular

Hi Dev,

This post will give you example of what is an interface in angular. you will learn angular 9/8/7 interface example. We will use interface in angular component. This post will give you simple example of how to use interface in angular component.

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 explaination 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.

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

How to Define Interface in Angular?

Here, i will show you very simple example how to define interface class in angular. you can see bellow code for defining 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...