1

I want to call a static class method/function from out of my HTML in Angular 7. This function is not in the component.ts but in a separate general class file message.ts. An error is displayed on the console :

TypeError: Cannot read property 'msg1' of undefined.

Template:

<div>
  {{ Message.msg1({ 'x': 'abc', 'y': 'def' }) }}
</div>

message.ts:

import { Injectable } from '@angular/core';

    @Injectable({
        providedIn: 'root'
    })
    export class Message {

        constructor() { }

        public static msg1 (items: []): string {
          // some code
        }
    }

Is what I want possible ? If yes, how can I get the message file (and so the Message class) in scope of the HTML?

7
  • What is the purpose? Commented Apr 19, 2019 at 7:33
  • You should use services for this Commented Apr 19, 2019 at 7:35
  • It is bad idea: if some property changed in your Message object, then template will be broken and you don't know about it; Commented Apr 19, 2019 at 7:42
  • Do you want that Message class as a global class and by which you can use a method of that class anywhere? Commented Apr 19, 2019 at 7:50
  • @Niraj Oza : yes, that's the purpose Commented Apr 19, 2019 at 11:42

1 Answer 1

4

Static methods are accessible on the class, not the instance injected by DI. If you want that template code to work, you'd have to do e.g.

import { Message } from ".../message";

@Component(...)
class Whatever {
  Message = Message;

   ...
}

to make the class available as Message in the template scope.

That said, it's unclear why that method is static, or what the point of an injectable service with only a static method is.

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

2 Comments

Yes, this works ... but at the end of the day I would like to have that Message class as a global class which I can use anywhere (html, component, service) without having to import/instantiatie/declare it.
I don't think you can do that, then; only components and pipes declared in the module and public properties on the component class are accessible from the template.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.