在 angular 2 中通过输入装饰器使用多个属性

Consuming multiple properties via Input decorator in angular 2

我的这个组件通过其选择器接收两个输入,但这可以扩展到任意数量的输入和任何组件。因此,为了在组件本身中使用多个属性,单个 @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>

那么,是否可以通过任何其他方式只对任意数量的输入道具使用单个装饰器?如果除了 waitFormessage 之外还有更多我要传递的道具,我是否必须为每个道具执行以下操作。

 @Input() waitFor: boolean;
 @Input() message: string;
 @Input() someOtherProp: string;
 ....

或者是否有任何其他方法可以只拥有一个 Input 装饰器并使用任意数量的属性?

如果您需要多个值,则不可能使用数组或其他东西

export class AsyncComponent {
     @Input() props: any[];

我同意 Roman 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' };
}

注意。请注意,在输入属性上声明的接口不是强制执行的。最好的做法是仍然声明它们,但 JavaScript 无法运行时检查 TypeScript 接口。此备注适用于此线程中的所有代码示例(单输入、多输入...)。