In Angular, services are commonly used to store and share data across components. By adding getters and setters to a service, you can:
[(ngModel)].private _username) to store data.A typical pattern for getters/setters in an Angular service looks like this:
// Generic service pattern using getter and setter
import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class ExampleService {
private _value: string = '';
get value(): string {
return this._value;
}
set value(newValue: string) {
this._value = newValue.trim();
}
}
The get and set keywords make value look like a normal property when used in components, but under the hood you can keep all your logic centralized in the service.
This service stores a username and trims extra spaces whenever it is updated.
// user.service.ts - manage a username with getter and setter
import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class UserService {
private _username: string = '';
get username(): string {
return this._username;
}
set username(value: string) {
this._username = value.trim();
}
}
The component injects UserService and binds the template input directly to userService.username.
// profile.component.ts - bind template to service property
import { Component } from '@angular/core';
import { UserService } from './user.service';
@Component({
selector: 'app-profile',
template: `
<h2>Hello {{ userService.username }}</h2>
<input [(ngModel)]="userService.username" placeholder="Enter Username">
`
})
export class ProfileComponent {
constructor(public userService: UserService) {}
}
Here, the setter validates the theme before updating it. Only 'light' and 'dark' are accepted.
// settings.service.ts - validate theme values in the setter
import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class SettingsService {
private _theme: string = 'light';
get theme(): string {
return this._theme;
}
set theme(value: string) {
if (['light', 'dark'].includes(value)) {
this._theme = value;
} else {
console.warn('Invalid theme value, keeping previous setting.');
}
}
}
ProfileComponent, Angular updates userService.username using the setter." Meghraj " becomes "Meghraj"), keeping the stored value clean.{{'{{ userService.username }}'}}, so the heading always shows the latest username: Hello Meghraj.SettingsService, if someone tries to set theme to "blue", the setter rejects it and logs a warning instead of breaking the app.In summary, components stay simple: they just read/write properties. All rules and checks live in the service.
BehaviorSubject or Observable when you need reactive updates (e.g. a getter returning theme$).isLoggedIn, setter for token.AuthService with:
isLoggedIn that returns true if a valid token exists,token that validates basic JWT format before storing it.CartService where a setter ensures item quantities are never negative and caps them at a maximum limit.SettingsService to include:
theme (already done), andisDarkMode that returns true when the current theme is 'dark'.