Is it good practice to use getter setter in angular 2 app

I am working on angular2 app in which my team member is using getter and setter to set input properties as follows

private _showModal;
@Input() set showModal(showModal){
     this._showModal = showModal;
}
get showModal() {
     return this._showModal;
}

      

but I'm not sure if this is a good way to do it. I thought I need to use getter setter in case the developer has to do some validation or check or perform some other function when setting or getting a value

+3


source to share


3 answers


I would only do this if you change the _showModal in get or set.

Using it like your team member (with property support) just adds more lines of code. In this case, I would make a public property showModal.



I don't know if there is a "best practice" for this. I think this is mainly due to personal preference.

0


source


This is part of the opinion, part of the requirements of your application. It is certainly a good idea to use getters and setters. But I would also use them with discretion, and in most cases getters and setters may not be needed.

In the code example below, there is no reason to use a getter and setter. You are correct that it can help when doing some kind of validation check or when something else depends on a set value, etc. For example, maybe you need to call some function when the value of a property @Input()

changes the value, this might be an easy way to achieve this. But in many cases this is probably not a requirement for every variable / input in your application.



Hope it helps.

0


source


This is a good practice as you have more control over your data. Especially when you need to know when your data has changed in angular change detection.

Most of the time I use them in my services to share data across multiple components.

They also interact well with observables so they don't have to call the endpoint multiple times to get your data.

0


source







All Articles