Angular tutorial question

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.

1 Like

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

3 Likes

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>
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.