newoperator on the class:
let myInstance = new myClass();. The instance created is an object on which you can call the class methods and get and set the values of its properties. Multiple instances can be created from one class.
OnInitis an interface - a structure defined but not implemented as a class. It defines which properties and/or methods should exist on the class that implements it. In this case,
OnInitis an interface for Angular Components which implement the method
ngOnInit. This method is a component life-cycle method. Angular will call this method after the component instance has been created.
ngOnInitmethod. You can see it also added the method in the body of the class:
OnInitinterface, but it's useful to use the implementation statement. To see why, delete the
ngOnInitmethod. The IDE will tell you there's an error - you must implement
ngOnInit. How does it know that? Because of
A strong feature in Angular that uses the constructor is dependency injection. We'll get to that later on, when we start using services.
titlewe added is used to store a value, in our case of type string. Each instance of the class will have its own
titleproperty, meaning you can change the value of
titlein one instance, but it will remain the same in the other instances.
titleis of the type
string. (The type is inferred by TypeScript when we immediately assign a value, so there's no need to add the type in this case.)
this. It's a special property that points at the current instance.
titlefrom inside the constructor. See the result in the browser:
titleinside the method
ngOnInit. Which value will be displayed on the screen?
titleaccording to the argument we will pass. We'll call it
changeTitle. The method will have one parameter of type
string. Add it inside the class body (but not inside another method):
changeTitleis not used anywhere yet. We can call it from another method or from the template (which we will see in the following chapters). Let's call it from the constructor.
ngOnInit. Try calling it before or after assigning a value directly to title. Try calling it a few times from the same method. See the result in the browser.
console.log(someValue)inside class methods. Then the value you passed as an argument will be printed in the browser's console. This way you can see the order of the execution of the methods and the value of the argument you pass (if it's a variable). For example: