代码之家  ›  专栏  ›  技术社区  ›  FllnAngl

如何从HTML调用外部typescript文件中的函数

  •  0
  • FllnAngl  · 技术社区  · 4 年前

    我试图访问我在一个单独的typescript文件中创建的函数,但我觉得我错过了一些东西,因为它不工作,也许是一些路由?

    我的输入字段:(在groepdef编辑组件.html内部)

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

    我导入了 export class Utils

    我的typescript文件:(在groepdef.edit.component.ts中)

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

    我的分离TS文件:

    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;
        }
      }
     }
    }
    
    1 回复  |  直到 4 年前
        1
  •  1
  •   Devang Patel    4 年前

    要访问该函数,您需要创建一个服务,并将该服务注入到您的组件中使用。

    服务(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;
         }
      }
    
    }
    

    现在,您需要将其注入并导入到您的组件(groepdef.edit.component.ts)中:

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

    在您的HTML(groepdef-edit component.HTML)中:

    <input type="number" (blur)="utilService.setTariefIfEmpty($event)"/>
    
        2
  •  1
  •   Siddhant    4 年前
    • 就你而言 Utils 不应定义为角度组件
    • 您可以创建 Utils.ts 文件并直接从中导出函数。当您的功能不依赖于任何其他Angular功能(例如任何Angular服务)时,这会很方便
        export someFunction(someArg: any): any {
           ...
        }
    
    • 您可以创建Angular服务 UtilityService 当您的函数有一些其他依赖项时,或者当您想执行组件通信或HTTP调用时
        @Injectable({
            providedIn: 'root',
          })
          export class UtilService { ... }
    

    就你而言 第2点 即导出功能应起作用。如果你遵循这种方法,那么你就可以利用你的组件中的函数 ts 文件为:

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

    HTML文件:

       <input type="number" (blur)="onBlur($event)" />
    
        3
  •  0
  •   Mario Petrovic Emmanuel Onah    4 年前

    模板文件未访问的原因 SetTariefIfEmpty() 是因为您没有在模块文件中声明单独的.ts文件。

    所以,在中声明你的Utils类 _modules.ts_ 文件

    推荐文章