concept setter in category angular

appears as: setter, setters, setter
Angular Development with Typescript, Second Edition

This is an excerpt from Manning's book Angular Development with Typescript, Second Edition.

Listing 8.3. Adding the setter and getter
...
private _stockSymbol: string;                    #1

@Input() set stockSymbol(value: string)          #2

  if (value !== undefined) {
    this._stockSymbol = value;
    console.log(`Buying ${this.quantity} shares of ${value}`);
  }
}

get stockSymbol(): string {                      #3
   return this._stockSymbol;
}

How can a component intercept the moment when the value of the input property stockSymbol changes to perform some additional processing? A simple way is to turn stockSymbol into a setter. If you want to use stockSymbol in the template of the component, create a getter as well, as shown in the following listing.

Listing 8.3. Adding the setter and getter
...
private _stockSymbol: string;                    #1

@Input() set stockSymbol(value: string)          #2

  if (value !== undefined) {
    this._stockSymbol = value;
    console.log(`Buying ${this.quantity} shares of ${value}`);
  }
}

get stockSymbol(): string {                      #3
   return this._stockSymbol;
}

When this application starts, the change detection mechanism qualifies the initialization as a change of the bound variable stockSymbol. The setter is invoked, and, to avoid sending an order for the undefined stockSymbol, you check its value in the setter.

A.11.4. Getters, setters, and method definitions

The syntax for the object’s getter and setter methods isn’t new in ES6, but let’s review it before going on to the new syntax for defining methods. Setters and getters bind functions to object properties. Consider the declaration and the use of the object literal Tax: