Call static function from angular2 template

后端 未结 4 2138
滥情空心
滥情空心 2020-12-05 06:22

I\'m trying to build \'utility\' services (classes) for an angular project. The utility classes have static functions (so we don\'t have to instantiate needless objects).

4条回答
  •  臣服心动
    2020-12-05 07:04

    Gunter's answer is perfectly valid and is the way I've done it most of the time.

    If you are using typescript, you additionally have the option of creating a custom decorator to provide functions to your view so your component remains uncluttered.

    Example:

    Define a decorator:

    import {StaticClassFunctions} from "./static-class-functions"
    
    export function CustomDecorator(): Function {
        return (target: Function): Function => {
            target.prototype.yourStaticMethod = (param1) => {
                return StaticClassFunctions.yourStaticMethod(param1);
            }
        }
    }
    

    Apply the decorator to your component:

    @Component{ ... }
    @CustomDecorator()
    export class YourComponent { ... }
    

    Now your have access to those static functions in your view without having to declare them in your Component! Very useful for repetitive "utility" functions to support view formatting and such (like enum casting!)

    {{yourStaticMethod(yourInput)}}
    

    You won't have access in your component though unless you declare the function at the top so it can compile.

提交回复
热议问题