Angular Components: Pass by Reference or Pass by Value?

Read full article on the Infragistics blog

In Angular, you can pass data from parent component to child component using @Input() decorator, and a child component can emit an event to a parent comment using @Output() decorator.

The purpose of this blog post is to explain you whether it is pass by reference or pass by value in context of @Input() and @Output decorator.

To start with, let us assume that we have two components, as listed below:


import { Component, Input } from '@angular/core';
@Component({
selector: 'app-video',
template: `
{{data.counter}} {{count}}
`
})
export class VideoComponent {
@Input() data: any;
@Input() count: number;
}


import { Component, Input } from '@angular/core';
@Component({
selector: 'app-video',
template: `
{{data.counter}} {{count}}
`
})
export class VideoComponent {
@Input() data: any;
@Input() count: number;
}

As you see, we have two input properties.

  1. In data property, we will pass an object.
  2. In count property, we will pass a number.

From the AppComponent, we are passing value for both properties, as shown below:


import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<app-video [data]='data' [count]='count' ></app-video>
`
})
export class AppComponent implements OnInit {
data: any = {};
count: number;
constructor() {
}
ngOnInit() {
this.data.counter = 1;
this.count = 1;
}
}

As you see,  we are passing data (object) and count( number) to the child component. Since data is being passed as object,  it will be “Pass by Reference” and, since count is passed as number,  it will be “Pass by Value”.

Therefore, if passing an object, array, or the like,  then it is Pass by Reference, and for primitive types like number, it is Pass by Value.

Read full article on the Infragistics blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com