I am working through the Angular tutorial and there is a get() getter method that I am not understanding how it is being called or better where it is being called from. Can someone assist please? This is the link to the tutorial Developer Mozilla
Well this is a definition of the getter function within a class. Itâs saying: âWhen someone tries to get the value of items
from the object, run this function.â
If you look into later examples (âCreating an item componentâ, for example) you will see that it makes references to things like {{items.length}}
, which is when it accesses the value.
TL;DR: In the code you reference, the getter is being called by the ngFor
in this line:
<li *ngFor="let item of items">{{item.description}}</li>
A slightly more detailed explanation:
In Angular interpolation allows you to render a component property in a view template. E.g.:
export class AppComponent {
firstName = 'John';
lastName = 'Jones';
}
and:
<p>Logged in as: {{firstName}}</p>
By default, interpolation uses the double curly braces {{
and }}
as delimiters.
Now imagine you wanted to display the first and the last name of the logged in user. You could do:
<p>Logged in as: {{firstName + ' ' + lastName}}</p>
While that would work, itâs messy and generally speaking it is a good idea to keep templates free of business logic.
Instead you could create a getter function to display the userâs full name.
export class AppComponent {
firstName = 'John';
lastName = 'Jones';
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
}
and:
<p>Logged in as: {{fullName}}</p>
Getter functions can also be called by NgFor
directives.
For example, this will output âTestâ 4 times:
export class AppComponent {
get items() {
console.log('In the getter');
return [ 1, 2, 3, 4 ];
}
}
and:
<ul>
<li *ngFor="let item of items">Test</li>
</ul>
But if you look in your browserâs console, you will also see that âIn the getterâ is logged.
And that is basically what is going on in the code you posted. It is using interpolation, but the getter function itself is being called by the NgFor
directive.
HTH
How would the code below output âtestâ 4 times and how is it that the function is never being called by its name?
export class AppComponent {
get items() {
console.log(âIn the getterâ);return [ 1, 2, 3, 4 ];
}
}
The ngFor
directive expects to find an items
property, or an items
getter method on the AppComponent
.
It finds the getter method and calls it. This returns an array with 4 elements. It then iterates over the items in that array and for each item it creates a new <li>
element containing the word âTestâ.
If you wanted to use the values from the array, you could reference them like so:
<ul>
<li *ngFor="let item of items">Test no. {{item}}</li>
</ul>