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

Angular中如何为Component.inputs数组的输入项定义类型?

在Angular的@Component inputs数组中为输入项定义类型

如果你在@Component的inputs数组中声明输入项,想要给这些输入项指定类型,只需要在组件类中显式声明对应的属性并添加TypeScript类型注解即可——inputs数组的作用只是告诉Angular把哪些类属性作为输入绑定,类型信息依然由类属性的定义来提供。

举个完整的示例:

import { Component, ChangeDetectionStrategy } from '@angular/core';

@Component({
   selector: 'my-component',
   changeDetection: ChangeDetectionStrategy.OnPush,
   template: '<ng-content></ng-content>',
   inputs: ['first', 'last', 'middle']
})
export class MyComponent {
  // 直接在这里给属性添加类型
  first: string;
  last: string;
  middle?: string; // 可选类型,允许未传入值
}

你也可以给属性设置默认值,同时保留类型:

export class MyComponent {
  first: string = '';
  last: string = '';
  middle?: string;
}

另外,如果需要给输入项设置别名(比如模板中用first-name绑定,类中用first接收),可以在inputs数组里用属性名:别名的写法,类型还是在类属性中定义:

@Component({
   // ...其他配置
   inputs: ['first:firstName', 'last:lastName']
})
export class MyComponent {
  first: string;
  last: string;
}

不过要注意,Angular官方更推荐使用@Input()装饰器的写法,因为它更直观,能直接在属性上看到输入绑定的标识,可读性更强。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 07:10:31