You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular输入信号调用报错:this.width is not a function

Angular输入信号调用报错:this.width is not a function

看起来你碰到了Angular输入信号使用的常见小坑!报错this.width is not a function说明你对输入信号的取值方式理解错了,咱们一步步捋清楚问题、解决它。

问题根源

你用readonly width = input<string>('');创建的是输入信号(Input Signal),但报错的原因分两种情况:

  • 如果你用的是Angular 17及以上版本:这个版本对输入信号做了简化,不需要通过()调用获取值,直接访问this.width就能拿到当前的输入值。你还在用this.width()的话,自然会报错说它不是函数。
  • 如果你用的是Angular 16版本:输入信号本质是Signal,必须通过this.width()调用取值,但报错说明你的width没有被正确初始化为Signal——大概率是代码里有冲突,比如同时用了@Input()装饰器和input()函数声明width,或者在组件元数据的inputs数组里重复定义了width,导致信号被覆盖成了普通属性。

解决办法

先搞清楚你的Angular版本(终端跑ng version就能看),然后对应调整:

  1. Angular 17+版本:直接去掉括号,把代码改成这样:
host.style.setProperty('--app-skeleton-width', this.width || '100%');
  1. Angular 16版本:
    • 确保只保留readonly width = input<string>('');这种信号声明,删掉任何@Input() width或者组件inputs数组里的width配置;
    • 确认input函数是从@angular/core正确导入的;
    • 保留this.width()的调用方式,代码如下:
import { Component, OnInit, input, Inject, PLATFORM_ID, ElementRef } from '@angular/core';
import { isPlatformServer } from '@angular/common';

export class SkeletonComponent implements OnInit {
  readonly width = input<string>('');

  constructor(
    @Inject(PLATFORM_ID) private platformId: Object,
    private host: ElementRef
  ) {}

  ngOnInit(): void {
    if (isPlatformServer(this.platformId)) {
      return;
    }

    const hostEl = this.host.nativeElement;
    hostEl.style.setProperty('--app-skeleton-width', this.width() || '100%');
  }
}

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.08 13:44:37