A method is a function defined by a class or object and invoked through that object or class. Instance methods use this to read or change the receiving object's properties; static methods belong to the class and cannot access instance fields, properties, or methods. section 4.4.2
Moving behavior into a Product class
Define printDetails inside Product, then call hat.printDetails() or boots.printDetails(). The method reads this.name, this.price, and this.category, producing the same details as the earlier standalone function. A subclass such as DiscountProduct inherits the method and can use it without redefining it.
Listing 4.24. Defining a method in the main.ts file in the src folder
class Product {
constructor(name: string, price: number, category?: string) {
this.name = name;
this.price = price;
this.category = category;
}
name: string
price: number
category?: string
printDetails() {
if (this.category != undefined) {
console.log(`Name: ${this.name}, Price: ${this.price}, `
+ `Category: ${this.category}`);
} else {
console.log(`Name: ${this.name}, Price: ${this.price}`);
}
}
}
let hat = new Product("Hat", 100);
let boots = new Product("Boots", 100, "Snow Gear");
// function printDetails(product : { name: string, price: number,
// category?: string}) {
// if (product.category != undefined) {
// console.log(`Name: ${product.name}, Price: ${product.price}, `
// + `Category: ${product.category}`);
// } else {
// console.log(`Name: ${product.name}, Price: ${product.price}`);
// }
// }
hat.printDetails();
boots.printDetails();
Inspect a complete TypeScript class that stores product data and formats it through an instance method. section 4.4.2
In Angular components, methods provide actions for templates. Event binding connects a button's (click) attribute to a component method; the method changes application data, and Angular reflects the new state in the browser. Custom pipes likewise perform their work in a transform method, whose result becomes the binding value. section 10.2.1 section 17.3
Listing 10.3. Defining a method in the component.ts file in the src/app folder
import { Component } from "@angular/core";
import { Model } from "./repository.model";
@Component({
selector: "app",
templateUrl: "template.html"
})
export class ProductComponent {
private model: Model = new Model();
private messages = ["Total", "Price"];
private index = 0;
get count(): number {
return this.model.getProducts().length;
}
get total(): string {
return this.model.getProducts()
.reduce((total, p) => total + (p.price ?? 0), 0).toFixed(2);
}
get message(): string {
return `${this.messages[this.index]} $${this.total}`;
}
toggleMessage() {
this.index = (this.index + 1) % 2;
}
removeProduct() {
this.model.deleteProduct(this.model.getProducts()[0].id ?? 0);
}
}
Inspect component methods that toggle displayed data or remove a product in response to template clicks. section 10.2.1



















