In JavaScript, getter and setter are powerful tool that allow you to manage how properties are accessed and modified in objects. They enable you to encapsulate logic for retrieving or updating values, providing cleaner and more maintainable codebase.
class MyClass {
constructor(value) {
this._value = value;
}
// Getter
get value() {
return this._value;
}
// Setter
set value(newValue) {
if (newValue > 0) {
this._value = newValue;
} else {
console.log('Value must be positive');
}
}
}
In my Angular project I use this get function to get image path dynamically.
//user.component.ts
import { Component } from '@angular/core';
import { DUMMY_USERS } from '../dummy-users';
const randomIndex = Math.floor(Math.random() * DUMMY_USERS.length )
@Component({
selector: 'app-user',
standalone: true,
imports: [],
templateUrl: './user.component.html',
styleUrl: './user.component.css'
})
export class UserComponent {
selectedUser = DUMMY_USERS[randomIndex]
get imagePath() {
return 'assets/users/' + this.selectedUser.avatar
}
}
<!-- user.component.html -->
<div>
<button>
<img [src]="imagePath"
[alt]="selectedUser.name">
<span>{{selectedUser.name}}</span>
</button>
</div>