简体   繁体   中英

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".

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM