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

标签 angular typescript angular-components angular-decorator

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

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

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

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

最佳答案

我同意 Roman C 的观点。

我只会传递一个包含所有 Prop 的对象(不是数组):

@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' };
}

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

关于angular - 通过 Angular 2 中的输入装饰器使用多个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42454734/

相关文章:

typescript - 如何使用对枚举通用的类扩展通用接口(interface)?

Angular 生成大型 react 形式的最佳方法是什么?

Angular 2 : Load different versions of the libraries based on the data

javascript - Angular 9无法发出post请求

javascript - 使用 NgRx,在状态对象中重置或返回空数组的正确方法是什么?

Angular 2 @progress/kendo-angular-grid 不适用于 webpack?

typescript - SvelteKit 中的 Pixi.js 仅在构建时出现 'self is not defined' 错误

javascript - Angular 2 - 无法将值传递给模型 - Javascript、Typescript

javascript - 如何检查 Angular 1.5 中是否存在组件

angular - 如何将 Angular 组件包裹在动态组件周围