Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass object from one component to another in Angular 2?

I have Angular components and first component uses the second one as a directive. They should share the same model object, which is initialized in the first component. How can I pass that model to the second component?

like image 822
Anoush Hakobyan Avatar asked Dec 04 '15 12:12

Anoush Hakobyan


People also ask

What is @input and @output in Angular?

@Input() and @Output() allow Angular to share data between the parent context and child directives or components. An @Input() property is writable while an @Output() property is observable.


2 Answers

For one-way data binding from parent to child, use the @Input decorator (as recommended by the style guide) to specify an input property on the child component

@Input() model: any;   // instead of any, specify your type 

and use template property binding in the parent template

<child [model]="parentModel"></child> 

Since you are passing an object (a JavaScript reference type) any changes you make to object properties in the parent or the child component will be reflected in the other component, since both components have a reference to the same object. I show this in the Plunker.

If you reassign the object in the parent component

this.model = someNewModel; 

Angular will propagate the new object reference to the child component (automatically, as part of change detection).

The only thing you shouldn't do is reassign the object in the child component. If you do this, the parent will still reference the original object. (If you do need two-way data binding, see https://stackoverflow.com/a/34616530/215945).

@Component({   selector: 'child',   template: `<h3>child</h3>      <div>{{model.prop1}}</div>     <button (click)="updateModel()">update model</button>` }) class Child {   @Input() model: any;   // instead of any, specify your type   updateModel() {     this.model.prop1 += ' child';   } }  @Component({   selector: 'my-app',   directives: [Child],   template: `     <h3>Parent</h3>     <div>{{parentModel.prop1}}</div>     <button (click)="updateModel()">update model</button>     <child [model]="parentModel"></child>` }) export class AppComponent {   parentModel = { prop1: '1st prop', prop2: '2nd prop' };   constructor() {}   updateModel() { this.parentModel.prop1 += ' parent'; } } 

Plunker - Angular RC.2

like image 134
Mark Rajcok Avatar answered Sep 28 '22 03:09

Mark Rajcok


Component 2, the directive component can define a input property (@input annotation in Typescript). And Component 1 can pass that property to the directive component from template.

See this SO answer How to do inter communication between a master and detail component in Angular2?

and how input is being passed to child components. In your case it is directive.

like image 43
Chandermani Avatar answered Sep 28 '22 02:09

Chandermani