- Creating Web Components in Angular - February 23, 2021
- What is your Communication Style? - August 1, 2020
- Sharing is caring? - January 28, 2020
This is part 4 of the Angular Tutorial for Beginners series.
A printable version of this article can be found here.
Part 1 of this series discussed how to get started with Angular.
Part 2 discussed about the basic tenets of Angular Modules, Components and Directives.
Part 3 discusses data binding.
Part 4 here builds up on the demo used in the earlier parts to explain the concept of interface. Hence it is strongly advised that you go through them before proceeding.
Interfaces in Typescript provide type checking. Here we have defined an array of any as below. But this does not provide any type checking.
For type checking we will create, an interface of employee as below.
We will create typescript file employee.ts and export an interface as below.
export interface IEmployee{
employeeId : number;
employeeName : string;
projectId : number
}
Let’s import the employee.ts in employee.component.ts.
Now we replace the array of any with an array of IEmployee in employee.component.ts as below.
Using an interface like IEmployee will provide me with a type checking. If I write ’employeeNames’ instead of ’employeeName’, I will be notified immediately as below. So, this helps in compile time checking and helps me to catch errors earlier on.
So, what if we use a class instead of an interface for type checking. There is no concept of interfaces in JavaScript. Hence when interfaces are transpiled, there is no code generated. But if we use classes, Javascript code is generated. Using interface, you can avoid this extra javascript code. If you only need to perform type checking, then using interfaces instead of classes is good option. is a good read to know more about Typescript classes & interfaces.
In the next part of the Angular tutorial for Beginners series we will learn how to use services in angular.
Contents of the Angular tutorial for Beginners series:
Part 2: Modules, Components & Directives in Angular.
Part 3: Data binding in angular.
Part 6: Http Requests with Observables.