【问题标题】:Consuming multiple properties via Input decorator in angular 2通过 Angular 2 中的 Input 装饰器使用多个属性
【发布时间】:2017-07-16 05:39:11
【问题描述】:

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

【问题讨论】:

  • 为什么要单输入,单输入是针对单值的。
  • @RomanC,假设我将 10 个道具传递给组件,这是否意味着我必须在组件本身中将装饰器包装 10 次?
  • 包装装饰器 10 次?不,这样不行。

标签: angular typescript angular-components angular-decorator


【解决方案1】:

我同意 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 接口。此注释适用于该线程中的所有代码示例(单输入、多输入...)。

【讨论】:

  • 谢谢。我对数组和其他答案有点困惑。
  • 顺便说一句,我刚刚看到您的界面使用说明,我并不完全理解。能否请您再解释一下?
  • 你可能知道你的 TypeScript 代码需要被转译成 JavaScript 才能在浏览器中执行。 TypeScript 接口在转译期间被删除,它们从最终的 JavaScript 代码中消失。换句话说,TypeScript 接口可用于 compile-time 类型检查,但不适用于 run-time 类型检查。在您的示例中,输入属性的值在编译时尚不清楚,仅在运行时才知道,这意味着接口并没有真正的帮助。保留它仍然是一个好习惯(用于代码文档、IDE 中的代码完成......)。
  • 这是非常有用的信息,真的。我真的很感激它,伙计。谢谢一百万。
【解决方案2】:

如果您需要多个值,则无法使用数组或其他东西

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

【讨论】:

  • 我认为我的问题有点混乱。非常感谢您的回答,但我已对问题进行了一些更新以使其更清晰。
猜你喜欢
  • 2017-03-15
  • 1970-01-01
  • 1970-01-01
  • 2018-03-29
  • 2021-05-17
  • 2020-03-03
  • 2020-10-16
  • 2019-11-22
  • 2019-08-08
相关资源
最近更新 更多