Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

132
Visualizações
Angular 2 templates methods vs getters

I'm wondering if there is any benefit to do this:

  <div>{{getSomething()}}</div>

  export class MyComp {
    getSomething() { return ...}
  }

Over this:

 <div>{{getSomething}}</div>

 export class MyComp {
   get getSomething() { return ...}
 }

Use methods vs getters to display calculated data.

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

I looked deeper into this and played with typescript Playground. I declared two classes one with getter and the second with get method as described in your questions.

Lets see how it looks like:

In the first example we declared a method for getting the property value in the following way:

class Greeter {
  greeting: string;
  constructor(message: string) {
      this.greeting = message;
  }
   getGreeting() {
      return this.greeting;
  }
}

Which after translation to javascript it looks like:

var Greeter = (function () {
   function Greeter(message) {
       this.greeting = message;
   }
   Greeter.prototype.getGreeting = function () {
       return this.greeting;
   };
   return Greeter;
}());

And regarding the second example where we declared a getter in the following way:

class GetterGreeter {
   _greeting: string;
   constructor(message: string) {
       this._greeting = message;
   }
    get greeting() {
       return this._greeting;
   }
}

Which after translation looks like:

var GetterGreeter = (function () {
   function GetterGreeter(message) {
       this._greeting = message;
   }
   Object.defineProperty(GetterGreeter.prototype, "greeting", {
       get: function () {
           return this._greeting;
       },
       enumerable: true,
       configurable: true
   });
   return GetterGreeter;
}());

(You can play with the declaration and the translation to javascript here)

As you can see with get method (as in your first example) the method is declared on the prototype and in your second example using the getter pattern typescript uses the defineProperty api.

In both cases we are invoking a method and angular will also call a method during its change detection to identify changes and re-render.

As I see it this is only a syntactic sugar for the same approach and I don't see any performance benefit for one of the methods.

about 4 years ago · Santiago Trujillo Relatório

0

If you are a getter or a method doesn't matter from a technical point of view.

Some use the convention that a getter should behave similar to a field, and not do expensive computation, while a method should be used if the computation is more than some very basic things like for example building a full name from first- middle- and last name.

I think this is good practice to follow that distinction for Angular, because for view binding expensive calculation should be avoided because the method or getter can be called very often. In such a case it's better to store the result in a field and bind to the field instead.

Very important in view binding is, that the method or getter doesn't return different values on subsequent calls when no dependencies were modified (like return {};, which would be treated as new object instance and cause an error like ExpressionChangedAfterItHasBeenCheckedError).

about 4 years ago · Santiago Trujillo Relatório

0

The difference is in the first case you use a function in expression, but in the second case it's not a function. So you can't use

<div>{{getSomething()}}</div>

export class MyComp {
  get getSomething() { return ...}
}

The benefits of using second method is to use encapsulation of the property inside the class and you need to access it outside the class.

Getters and setters are part of ES5 spec. You can read about getter and setter.

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda