liveBook · Manning

Constructor method

As explained in Pro Angular 16

A constructor is a class member that initializes an instance when the class is instantiated.

A constructor runs when a class is instantiated. It receives the arguments passed to `new` and performs the setup needed for the new object. In TypeScript, the constructor is named with the `constructor` keyword, not the class name. section 4.4.2 section 2.3.1

Listing 4.23. Defining a class 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
}

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}`);    
    }
}

printDetails(hat);
printDetails(boots);

Compare the two `new Product(...)` calls. The constructor assigns each argument to a property through `this`; the optional category can be omitted. Both resulting objects can be passed to a function expecting those properties. section 4.4.2

When constructor arguments simply become properties, TypeScript offers a shorter form: put `public` on each parameter and omit the separate property declarations and assignments. A parameter can also have a default value, as `complete` does in `TodoItem`. In a subclass, `super(...)` calls the parent constructor; `DiscountProduct` passes it a price after subtracting the discount. section 4.4.2 section 2.3.1

Listing 18.9. Declaring a dependency in the discountDisplay.component.ts file in the src/app folder
import { Component, Input } from "@angular/core";
import { DiscountService } from "./discount.service";
 
@Component({
    selector: "paDiscountDisplay",
    template: `<div class="bg-info text-white p-2 my-2">
                  The discount is {{discounter.discount }}
               </div>`
})
export class PaDiscountDisplayComponent {
 
    constructor(public discounter: DiscountService) { }

    // @Input({alias: "discounter", required: true})
    // discounter!: DiscountService;
}

Constructors also declare Angular dependencies. Here, `discounter: DiscountService` tells Angular which service the component needs, while `public` makes it available to the template. This replaces passing the shared object through an input property. section 18.2.2

How Pro Angular 16 covers it

How deep it goes
Works through property assignment, TypeScript parameter properties, inherited initialization, and Angular's inspection of constructor argument types.
Examples
Creates products with optional categories and discounted subclasses, then injects a discount service into display and editor components.
What it assumes
Introduces the syntax without assuming familiarity with JavaScript or TypeScript class features.
What you can do after
Build it from scratch to initialize TypeScript objects, or apply it in Angular to request a service through a component constructor.
How it connects
Connects classes and inheritance to TypeScript parameter properties, Angular services, and dependency injection.

Also explained in

Compare how 13 books explain constructor method →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro Angular 16. The section links point to the parts of the book it draws on.