Class WorkAround in Angular
Hi Friends, This is Lakshman here.
As part of the Series "Angular Best Practices".
Today, We will Class WorkAround in Angular.
Pre-requisites:
The pre-requisites are
- Node.JS - Click Here
- Angular CLI - Click Here
- VS Code - Click Here
Class
As predominantly angular uses class on many ways such as Modules, Components, Service & lot.
Now, we are going to see how we could use Class in Angular.
Class WorkArounds
Let us see some workaround,
1. Class Vs Interface
We need to use a class instead of an interface.
When we use an interface, it needs to declare its property whenever we create an instance. If we use class, we may use a constructor to set default values and set properties for class, as below,
export interface <InterfaceName> {
<property1>: string;
<property-2>: string;
}
export class <ClassName> implements <InterfaceName> {
<property1>: string;
<property-2>: string;
constructor() {
this.<property1> = null;
this.<property2> = null;
}
}
2. Mapper for Property binding
As we are using class, it helps to can create a property binder or mapper for class.
Nowadays, we fetch data from API. Currently, we need to create the extract same property name to use in components.
With the help of Mapper, we can map the response json to class property via mapper it set value automatically as below,
export interface <InterfaceName> {
<property1>: string;
<property-2>: string;
}
export class <ClassName> implements <InterfaceName> {
@propertyMap('<mapName1>')
<property1>: string;
@propertyMap('mapName2')
<property-2>: string;
constructor() {
this.<property1> = null;
this.<property2> = null;
}
}
While creating the instance of the object, we can use mapper as below,
...
const rtnItem = new ModelMapper(<ClassName>).map(<item>);
return rtnItem;
...
Check out the Mapper Base Class - Click Here
That wraps up the Class WorkAround in Angular
You may also access to source code on GitHub by Click Here
On-road head, we will discuss a lot of things.
Looking forward to your comments and share your feedback.
Until that, I am Lakshman, Signing Off.
Comments
Post a Comment