我有这个组件通过其选择器接收两个输入,但这可以扩展到任意数量的输入和任何组件.因此,在组件本身消耗多个属性的过程中,单个@Input()装饰器不允许我使用多个属性,因此作为一种解决方法,我使用了两个装饰器用于两个输入属性,但我不认为这将是解决这种情况的唯一方法.
export class AsyncComponent { @Input() waitFor: boolean; @Input() message: string; // TODO: Verify if multiple inputs are needed for multiple props }
更新
<app-async [waitFor]="true" message="foo"><app-async>
那么,是否有可能用任何其他方式只使用一个装饰器来获取任意数量的输入道具?如果我传递的道具比waitFor更多,那么我必须为每个道具执行以下操作.
@Input() waitFor: boolean; @Input() message: string; @Input() someOtherProp: string; ....
解决方法
我同意罗曼C.
我只传递一个包含所有道具的对象(不是数组):
@Component({ selector: 'app-async' }) export class AsyncComponent { // Single object with all props. @Input() props: { waitFor: boolean; message: string; }; }
然后是父组件:
@Component({ template: '<app-async [props]="myProps"><app-async>' }) export class ParentComponent { myProps = { waitFor: true,message: 'foo' }; }
NB.请注意,在输入属性上声明的接口不是ENFORCED.最佳做法是仍然声明它们,但JavaScript无法运行时检查TypeScript接口.此注释适用于此线程中的所有代码示例(单个输入,多个输入…).