mtnp
mtnp

Reputation: 379

Pass specific properties of an object to the child component with Input decorator

Assuming I have an object Customer as following :

export class Customer {

   id: number;
   name: string;
   premium: boolean;

   address: string;
   country: string;
}

In my parent component :

/*** stuff declaration */

@ViewChild(ChildComponent)
private childComponent: ChildComponent;

customer: Customer;

Child component :

/*** Stuff */

@Input()
public customerSubpart : any;

/*
customerSubpart properties expected:
id, name, premium
*/

save() : void {
   /* call service to save modifications */
}

I want that a click event on the parent template saves modifications done on the customerSubpart object within the save() method. I can manage that with @ViewChild decorator but I need to pass only a subpart of the customer object to the customerSubpart object. Do I really need to create a new model and inject it in the Customer model (or use inheritance) or there are cleaner ways to do that (best practices) ?

Upvotes: 0

Views: 634

Answers (1)

PMO1948
PMO1948

Reputation: 2554

If you wanted to avoid creating another model, you could pass it in as an anon type. For instance, by passing

   { id: customer.id, name: customer.name, premium: customer.premium }

This, however, is not a good practice because you lose the typing advantage of Typescript.

Another solution that could serve your purpose, depending on how many properties you have to send, is to create an @Input() per property. So for instance, instead of @Input() public customerSubpart : any; you could do

  @Input() id: number;
  @Input() name: string;
  @Input() premium: boolean;

A third option is to make the non- subpart properties optional properties, and then only send the properties you need. So your class would change to

export class Customer {

   id: number;
   name: string;
   premium: boolean;

   address?: string;
   country?: string;
}

This still runs the risk of your child component changing the latter properties accidentally, unless you forcibly stop it.

My recommendation would be to either use the second option or create a sub-Model, unless you do not need to fear the changes, in which case the third option would work too.

Good Luck!

Upvotes: 1

Related Questions