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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component, Input } from '@angular/core'; | |
@Component({ | |
selector: 'app-video', | |
template: ` | |
{{data.counter}} {{count}} | |
` | |
}) | |
export class VideoComponent { | |
@Input() data: any; | |
@Input() count: number; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.
- In data property, we will pass an object.
- In count property, we will pass a number.
From the AppComponent, we are passing value for both properties, as shown below:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.
Leave a Reply