Home > Blockchain >  how to call functions in external typescript file from HTML
how to call functions in external typescript file from HTML

Time:12-31

I'm trying to reach a function that I created in a seperate typescript file but I feel like I'm missing something because it's not working, maybe some routing?

My inputfield: (inside groepdef-edit-component.html)

<input type="number" (blur)="Utils.SetTariefIfEmpty($event)"

I imported the export class Utils

My typescript file: (inside groepdef.edit.component.ts)

import { Utils } from '../Utils/Utils';

My Seperate TS file:

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

@Component({
selector: 'app-utils',
templateUrl: './groeperingdefinitie-contract-edit.component.html',
})

export class Utils {

  public static SetTariefIfEmpty(event: any): void {
  if (event === undefined || event === null) {
    return;
  }

  if (event.target !== undefined && event.target !== null) {
    if (event.target.value.length == 0) {
      event.target.value = 0;
    }
  }
 }
}

CodePudding user response:

To access the function, you will need to create a service and inject that service into your component to use.

service (util.service.ts)

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

@Injectable({
  providedIn: 'root',
})

export class UtilService {

  public setTariefIfEmpty(event: any): void {
     if (event === undefined || event === null) {
       return;
     }
  }

}

Now you need to inject and import this into your component (groepdef.edit.component.ts):

import { UtilService } from '..PATH';
......
constructor(public utilService:UtilService) {}

In your HTML (groepdef-edit-component.html):

<input type="number" (blur)="utilService.setTariefIfEmpty($event)"/>

CodePudding user response:

  • In your case Utils should not be defined as an Angular Component
  • You can create Utils.ts file and export functions from it directly. This can be handy when your functions don't rely on any other Angular features(eg. any Angular service)
    export someFunction(someArg: any): any {
       ...
    }
  • You can create an Angular service UtilityService when your function has some other dependencies or in case when you want to perform component communication or maybe HTTP calls
    @Injectable({
        providedIn: 'root',
      })
      export class UtilService { ... }

In your case 2nd point i.e exporting functions should work. If you follow that approach, then you can utilize the function in your component ts file as:

    import { someFunction } from '<path_to_Utils.ts>';
     @Component({...})
     export class YourComponent {
       onBlur(event: Event) {
          someFunction(event);
       }
     }

HTML file:

   <input type="number" (blur)="onBlur($event)" />

CodePudding user response:

The reason that your template file is not accessing your SetTariefIfEmpty() is that you haven't declared your separate .ts file in your module file.

So, declare your Utils class in _modules.ts_ file.

  • Related