我正在嘗試訪問我在單獨的打字稿檔案中創建的函式,但我覺得我錯過了一些東西,因為它不起作用,也許是一些路由?
我的輸入欄位:(在 groepdef-edit-component.html 中)
<input type="number" (blur)="Utils.SetTariefIfEmpty($event)"
我匯入了 export class Utils
我的打字稿檔案:(在 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;
}
}
}
}
uj5u.com熱心網友回復:
要訪問該功能,您需要創建一個服務并將該服務注入到您的組件中以供使用。
服務(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)"/>
uj5u.com熱心網友回復:
- 在您的情況下,
Utils不應將其定義為 Angular Component - 您可以
Utils.ts直接從中創建檔案和匯出功能。當您的函式不依賴任何其他 Angular 功能(例如任何 Angular 服務)時,這會很方便
export someFunction(someArg: any): any {
...
}
UtilityService當您的函式具有其他一些依賴項時,或者您想要執行組件通信或 HTTP 呼叫時,您可以創建 Angular 服務
@Injectable({
providedIn: 'root',
})
export class UtilService { ... }
在您的情況下,第二點即匯出功能應該有效。如果您遵循這種方法,那么您可以將組件ts檔案中的函式用作:
import { someFunction } from '<path_to_Utils.ts>';
@Component({...})
export class YourComponent {
onBlur(event: Event) {
someFunction(event);
}
}
HTML檔案:
<input type="number" (blur)="onBlur($event)" />
uj5u.com熱心網友回復:
你的模板檔案沒有訪問你的原因SetTariefIfEmpty()是你沒有在你的模塊檔案中宣告你單獨的 .ts 檔案。
因此,在_modules.ts_檔案中宣告您的 Utils 類。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/398035.html
