Search code examples
templatesdartangular-dartangular2-dartdart-angular-templates

Angular 2 Dart Template syntax: How to access static methods?


Is there a way to access static methods from a template in Dart?

Problem is as follows:

offer.dart:

class Offer {
  static String getPriceString(double price) {
    return euroFormat.format(price) + " €";
  }
}

First Try:

main_component.html:

<div class="offer" *ngFor="let offer of offers">
 <span class="offer_price">{{ offer.getPriceString(1.9) }}</span>
</div>

Exception:

EXCEPTION: NoSuchMethodError: Class 'Offer' has no instance method 'getPriceString'. Receiver: Instance of 'Offer' Tried calling: getPriceString(4.9)

Second Try:

main_component.html:

<div class="offer" *ngFor="let offer of offers">
 <span class="offer_price">{{ Offer.getPriceString(1.9) }}</span>
</div>

Exception 2:

EXCEPTION: NoSuchMethodError: Class 'MainComponent' has no instance getter 'Offer'. Receiver: Instance of 'MainComponent' Tried calling: Offer

If I remove the static keyword from getPriceString() everything works like called in "First Try" but it feels not nice because I lose the possibility for static call.


Solution

  • The scope for binding expressions is the components class instance.

    If you want to access something from outside that scope you need to provide a means to access it through the components class instance (like a getter)

    class MyComponent {
      String get someStaticProp => SomeClass.someStaticProp;
    }
    

    then you can access it in view bindings like

    <div>{{someStaticProp}}</div>