squadwuschel
squadwuschel

Reputation: 3428

Angular 2 component parent-child communication with objects

When you create a parent component and a child component when you assign a primitive value (string, number, boolean) to the child component then you have to create a @Input and a @Output with eventemitter to get a two way communication. So far so good.

But when I assign a complex Object to my child component only with @Input and I change some values inside the Object then I also see these changes in my Parent component. Because I am editing a object reference.

So my Question is, should I avoid to set complex objects in my child components or is this a bad practice? Are there any pittfalls or is it ok to use it like a "two way databinding".

Upvotes: 0

Views: 637

Answers (1)

Aravind
Aravind

Reputation: 41571

Create a model with the relvant properties

export interface InputModel {
      a:string; 
      b:number;
      c:boolean;
}

Create a @Input property of this type

@Input() obj : InputModel

By this way any change to any property of your Input object. ngOnChanges() will be triggered which can be used to handle your operations

Upvotes: 1

Related Questions