简体   繁体   English

从HTML调用静态TypeScript函数

[英]Call static TypeScript function out of HTML

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 . 我想从Angular 7的HTML中调用静态类方法/函数。此函数不在component.ts而是在单独的常规类文件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 : 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? 如果是,如何获取HTML范围内的消息文件(以及Message类)?

Static methods are accessible on the class , not the instance injected by DI. 静态方法可在上访问,而不能由DI注入实例。 If you want that template code to work, you'd have to do eg 如果您希望该模板代码正常工作,则必须执行例如

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

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

   ...
}

to make the class available as Message in the template scope. 使该类可作为模板范围中的Message使用。

That said, it's unclear why that method is static, or what the point of an injectable service with only a static method is. 也就是说,尚不清楚该方法为何是静态的,或者仅静态方法的可注入服务的意义是什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM