Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to keep utility functions in angular2 that are available in templates

I have a few simple "pure" utility functions in my app which i want to keep in one place. The problem is, i can import them in my components by using:

import { utilities } from '../shared/utilities'

However these utility function/methods are not available in my template files (because they are bound to the component class only). I have to create an alias of these functions in my component in order to use them. Is there a better way to do this?

like image 597
Hassan Avatar asked Apr 04 '17 11:04

Hassan


People also ask

What is utility function in Angular?

The Angular testing utilities include the TestBed , the ComponentFixture , and a handful of functions that control the test environment. The TestBed and ComponentFixture classes are covered separately.

What are the elements that we can use in Angular templates?

This template uses typical HTML elements like <h2> and <p> . It also includes Angular template-syntax elements, *ngFor , {{hero.name}} , (click) , [hero] , and <app-hero-detail> . The template-syntax elements tell Angular how to render the HTML to the screen, using program logic and data.

What are templates in Angular with example?

A template is a form of HTML that tells Angular how to render a component. Views are usually organized hierarchically, allowing you to modify or show and hide entire UI sections or pages as a single unit. The template immediately associated with a component defines the host view of that component.


1 Answers

I think you should be able to use the utilities in the template if you inject it in your controller. Something like this :

import { Utilities } from './shared/utils';

@Component({
    ....
    ....
})
export class ExampleComponent {
    constructor(public util: Utilities) { }
}

In your template you should be able to use util.your_function

Update:

export class ExampleComponent {
    constructor(public util: Utilities) { }

    get staticMethod1() { return Utilities.staticMethod1(); }
}
like image 174
Vinit Sarvade Avatar answered Oct 17 '22 23:10

Vinit Sarvade