Angular TypeScript Component Logic
In Angular components, getters and setters let you run extra logic whenever a property is read or updated. They are useful for:
fullName from first and last name)get keyword and runs whenever the property is read (e.g., in template bindings like {{ fullName }}).set keyword and runs whenever the property is assigned (e.g., via [(ngModel)] or in TypeScript code)._firstName) and expose them through public getters/setters.{{ }} and two-way binding [(ngModel)].A basic getter/setter pair in a TypeScript (Angular) component looks like this:
// Simple getter and setter pattern in a component
private _value: string = '';
get value(): string {
// Compute or transform data before returning
return this._value.toUpperCase();
}
set value(newValue: string) {
// Validate or sanitize input before storing
this._value = newValue.trim();
}
Key points:
This component stores first and last name using private fields and exposes them with getters/setters. It also computes a fullName using a getter.
// user.component.ts - using getters/setters and a computed fullName
import { Component } from '@angular/core';
@Component({
selector: 'app-user',
template: `
<h2>Welcome {{ fullName }}</h2>
<input [(ngModel)]="firstName" placeholder="First Name">
<input [(ngModel)]="lastName" placeholder="Last Name">
`
})
export class UserComponent {
private _firstName: string = '';
private _lastName: string = '';
get firstName(): string {
// Expose the private _firstName field
return this._firstName;
}
set firstName(value: string) {
// Trim whitespace before storing the value
this._firstName = value.trim();
}
get lastName(): string {
// Expose the private _lastName field
return this._lastName;
}
set lastName(value: string) {
// Also trim whitespace for the last name
this._lastName = value.trim();
}
get fullName(): string {
// Compute a derived property from first and last name
return this.firstName + ' ' + this.lastName;
}
}
Here, the setter ensures that the product price can never be negative. If the user enters a negative value, the setter forces it back to 0.
// product.component.ts - using a setter to validate numeric input
import { Component } from '@angular/core';
@Component({
selector: 'app-product',
template: `
<p>Product Price: {{ price }}</p>
<input type="number" [(ngModel)]="price">
`
})
export class ProductComponent {
private _price: number = 0;
get price(): number {
// Return the validated price value
return this._price;
}
set price(value: number) {
// Prevent negative prices from being stored
if (value < 0) {
this._price = 0;
} else {
this._price = value;
}
}
}
First Name input:
[(ngModel)]="firstName" calls the setter with the new value._firstName.fullName is called, recomputing the full name.Welcome John Doe (for example).-50:
price receives -50.if check detects that it is negative and stores 0 instead.Product Price: 0.fullName, formatted currency, or combined labels._price) to avoid infinite loops or accidental recursion in setters.null and undefined carefully to avoid runtime errors.StudentComponent with firstName and lastName setters that automatically capitalize names (e.g., john → John).TemperatureComponent that stores temperature in Celsius but exposes a getter for Fahrenheit (and optionally a setter that converts back).username property with a setter that rejects empty strings and replaces them with a default username like "Guest".console.log) to see how often they are called during change detection.