如何从HTML调用外部TypeScript文件中的函数?Angular组件调用工具类静态函数失效问题排查
Utils.SetTariefIfEmpty Function Not Working in Angular Hey there! The problem here has nothing to do with routing—let's break down what's going wrong and how to fix it quickly.
The Root Issue: Misusing @Component on Your Utils Class
Your Utils class is marked with the @Component decorator, but this is completely unnecessary for a utility class. Angular uses @Component to define UI components with templates/selectors, but your Utils is just a plain helper class with static methods. This decorator is actually causing conflicts that prevent your static method from being accessed correctly.
Step-by-Step Fix
1. Rewrite Your Utils.ts File
Remove the @Component decorator and all related metadata—you don't need any of that for a utility class. We can also tighten up the type definitions to avoid any (a TypeScript best practice):
// ../Utils/Utils.ts export class Utils { public static SetTariefIfEmpty(event: FocusEvent): void { // Early return if event is null/undefined if (!event) return; // Type-cast the target to HTMLInputElement for better type safety const inputTarget = event.target as HTMLInputElement; if (inputTarget && inputTarget.value.length === 0) { inputTarget.value = '0'; } } }
2. Verify Your Component Import and Template Binding
Your existing import in groepdef.edit.component.ts is correct—no changes needed here:
import { Utils } from '../Utils/Utils';
And your template binding can stay exactly as it is:
<input type="number" (blur)="Utils.SetTariefIfEmpty($event)">
Why This Works
By removing the @Component decorator, we're telling Angular to treat Utils as a standard TypeScript class, not a UI component. This allows you to access its static methods directly in your template without any Angular-specific loading or initialization issues.
Bonus: Optional Type Safety Tip
Using FocusEvent (the correct type for blur events) instead of any gives you better IntelliSense and catches potential errors early. Casting the target to HTMLInputElement also ensures you're only accessing properties that exist on input elements, avoiding accidental bugs.
内容的提问来源于stack exchange,提问作者FllnAngl

