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
相关产品推荐
相关产品推荐

