3

My class is like this:

export class Image {
  static getUrl(x: Image) {
      return CONFIG.host + x.url
  }

  constructor(private url: string, public alt: string) {}
}

My template is like:

<img [src]="Image.getUrl(image)" [alt]="image.alt" >

My component is like:

export class MyComponent {
  image: Image;
  Image = Image;
}

For the moment I have to pass the class itself Image manually to the component, in order by use Image.getUrl. What's a standard way to use a custom function or class method in a template?

If I use instance methods, then if I receive a Json that contains a property looks like Image, I have to do a proper type cast before calling the method, which is not very convenient if it is in a nested json.

4
  • Why does the method definition need to be like that? It makes a lot more sense just to make it an instance method with no parameters, and just call the method on the instance, using the instance url. Commented Jul 26, 2016 at 11:17
  • You could also just do get url() { }. That way you can just access it like a regular property. image.url Commented Jul 26, 2016 at 11:19
  • 1
    @peeskillet Because if I add instance method it is no longer compatible with json like objects automatically. Commented Jul 26, 2016 at 11:34
  • @colinfang I want to do that too... I end up with the same Image=Image workaround.. :( Commented Sep 27, 2021 at 0:23

1 Answer 1

3

As far as I know, there is no way to refer to global variables/classes inside template. The scope of template is within its hosting Component.

Either you make it non-static getter of the Image class or define a custom pipe to help you with transforming Image to imageUrl.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.