angulartypescriptangular-componentsangular-decorator

Consuming multiple properties via @Input() decorator in Angular 2


I have this component that receives two inputs via its selector, but this can be extended to any number of inputs and any component. So, in quest of consuming multiple properties in the component itself a single @Input() decorator did not allow me to consume multiple properties, so as a workaround I used two decorators for two input properties, but I don't think this would be the only way to tackle such a scenario.

export class AsyncComponent {
     @Input() waitFor: boolean;
     @Input() message: string; // TODO: Verify if multiple inputs are needed for multiple props
 }

Update:

<app-async [waitFor]="true" message="foo"><app-async>

So, is it possible, with any other way, to just use a single decorator for any number of input props? If there are more props that I am passing other than waitFor and message, would I have to do the following for each prop.

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

Or is there any other way to just have one Input decorator and consume any number of properties?


Solution

  • I agree with Roman C.

    I would just pass a single object (not array) containing all props:

    @Component({
      selector: 'app-async'
    })
    export class AsyncComponent {
      // Single object with all props.
      @Input() props: { waitFor: boolean; message: string; };
    }
    

    And then the parent component:

    @Component({
      template: '<app-async [props]="myProps"><app-async>'
    })
    export class ParentComponent {
      myProps = { waitFor: true, message: 'foo' };
    }
    

    NB. Be aware that interfaces declared on input properties are NOT ENFORCED. It is best practice to still declare them, but JavaScript can't runtime-check a TypeScript interface. This remark applies to all code samples in this thread (single input, multiple inputs...).