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

Angular 19库使用input信号触发NG0203错误求助

问题

在Angular 19应用项目中,通过npm link引入另一个独立的Angular 19库项目时,生产构建阶段出现以下运行时错误(需在angular.json中设置"optimization": false才能复现):

ERROR Error: NG0203: inputFunction2() can only be used within an injection context such as a constructor, a factory function, a field initializer, or a function used with runInInjectionContext.

开发环境用npm run start启动时应用运行正常,问题出在组件中的input信号:

label = input<string>('');

移除该信号后恢复正常,尝试使用@Input结合Signal也会出现类似错误。疑问:Angular库中无法使用Signals吗?

复现步骤

  • 创建Angular 19库项目:
    ng new components --create-application=false
    ng generate library my-components
    ng generate component my-components/info-tooltip
    
  • 通过npm link将库引入应用项目(开发环境运行正常)。
  • 复现问题的InfoTooltipComponent极简版本:
    import { Component, input, ViewEncapsulation } from '@angular/core';
    
    @Component({
      selector: 'app-info-tooltip',
      imports: [],
      template: '<p>{{label()}}</p>',
      styles: [],
      encapsulation: ViewEncapsulation.ShadowDom,
    })
    export class InfoTooltipComponent {
      label = input<string>('');
    }
    
  • 应用项目中使用该组件的代码:
    import { Component } from '@angular/core';
    import { InfoTooltipComponent } from 'my-components';
    
    @Component({
      selector: 'app-test',
      imports: [InfoTooltipComponent],
      template: `
        <app-info-tooltip label="Hello, World!"></app-info-tooltip>
      `,
      styles: [],
    })
    export class TestComponent {
    }
    

解决方案

这个问题并非Angular库不能使用Signals,而是npm link导致的依赖重复或构建配置异常,以下是可行的修复方案:

1. 统一库与应用的Angular依赖

npm link可能导致库和应用各自加载独立的Angular核心包,破坏注入上下文的共享:

  • 在应用项目中执行npm link ../path-to-your-library/node_modules/@angular/core,强制应用复用库的Angular核心依赖;
  • 或直接在应用的package.json中,将库的依赖路径设为本地相对路径(如"my-components": "file:../components/projects/my-components"),替代npm link。

2. 调整库的构建配置

在库项目的angular.json中,开启preserveSymlinks配置:

{
  "projects": {
    "my-components": {
      "architect": {
        "build": {
          "options": {
            "preserveSymlinks": true
          }
        }
      }
    }
  }
}

3. 显式绑定注入上下文(临时兼容方案)

如果上述方法无效,可在组件中手动用runInInjectionContext包裹Signal创建逻辑:

import { Component, input, ViewEncapsulation, inject, runInInjectionContext } from '@angular/core';

@Component({
  selector: 'app-info-tooltip',
  imports: [],
  template: '<p>{{label()}}</p>',
  styles: [],
  encapsulation: ViewEncapsulation.ShadowDom,
})
export class InfoTooltipComponent {
  private injector = inject(Injector);
  label = runInInjectionContext(this.injector, () => input<string>(''));
}

4. 修正库的依赖声明

确保库的package.json中,Angular相关依赖(@angular/core、@angular/common等)仅存在于peerDependencies,而非dependencies:

{
  "peerDependencies": {
    "@angular/core": "^19.0.0",
    "@angular/common": "^19.0.0"
  }
}

内容的提问来源于stack exchange,提问作者Thomas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 06:03:16