Pass key-value pairs of object as individual arguments to component in Angular

36 views Asked by At

Assume i have a component that takes three inputs input1, input2 and input3

export class testComponent {
  @Input() input1:string;
  @Input() input2:string;
  @Input() input3:string;
  ....
  ...
}

In the parent component I have object like

args = {
    input1: "string1",
    input2: "string2",
    input3: "string3"
}

what is the best way to pass these key value pairs in object as arguments to the testComponent. All the inputs to testComponent are not mandatory and the args sometimes might not have all the arguments.

I don't want the testComponent to take object itself as the input. Pls suggest some ideas. Thankyou.

2

There are 2 answers

2
Naren Murali On BEST ANSWER

You have to do it manually, it's a limitation of Angular, like we cannot de-structure the object (...args) on the html tag and the child component will read the values like how React does!

<app-test [input1]="args?.input1" [input2]="args?.input2" [input3]="args?.input3"/>
0
Lautaro Lorenz On

In Naren Murali's answer, conditional chaining is unnecessary because arguments always exist; Actually, it should be like the following:

Parent component

<app-test 
  [input1]="args.input1" 
  [input2]="args.input2" 
  [input3]="args.input3"
></app-test>

Child component

export class testComponent {
  @Input() input1: string | undefined;
  @Input() input2: string | undefined;
  @Input() input3: string | undefined;
}

If you want to guarantee the string type of the inputs, you must define a default value, such as:

Child component

export class testComponent {
  @Input() input1 = '';
  @Input() input2 = '';
  @Input() input3 = '';
}