Encountering an interesting issue that I need clarification on. Recently, I developed a compact Angular application to demonstrate the problem at hand.
The puzzling situation arises when passing an Array (any[] or Object[]) as an @Input property to a child component and modifying a value within the Child. Surprisingly, these alterations are reflected in the Parent as well. As per my understanding from the documentation, this behavior should involve one-way binding requiring an @Output property (EventEmitter) from the child to transmit changes back to the parent.
To illustrate my point, I have included code samples. The provided snippet assigns two properties to the child component - an array of Objects and a plain text string. By utilizing an input field, I attempt to modify the Name1 value along with the plain text content.
This predicament raises the question: Why do adjustments made to the data array reflect in the parent, while modifications to the text string do not show up? Is there any detailed explanation in the documentation or can someone clarify the reason behind this discrepancy?
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
arr = [
{name: 'Name1', data: 'This is data 1..'},
{name: 'Name2', data: 'This is data 2..'},
{name: 'Name3', data: 'This is data 3..'},
];
someText = 'This is text';
}
app.component.html
<div style="border: 1px solid grey; padding: 4px;">
<h4>Parent</h4>
<ul>
<li *ngFor="let item of arr">Name: {{ item['name'] }}, Data: {{ item['data'] }}</li>
</ul>
<strong>{{ someText }}</strong>
</div>
<child-component [arr]="arr" [someText]="someText"></child-component>
child-component.component.ts
import {Component, Input} from '@angular/core';
@Component({
selector: 'child-component',
templateUrl: './child-component.component.html',
styleUrls: []
})
export class ChildComponentComponent {
@Input() arr: any[];
@Input() someText: string;
sendChanges(changes: any) {
this.arr[0]['name'] = changes;
this.someText = changes;
}
}
child-component.component.html
<div style="border: 1px solid grey; padding: 4px;">
<h4>Child</h4>
<ul>
<li *ngFor="let item of arr">Name: {{ item['name'] }}, Data: {{ item['data'] }}</li>
</ul>
<div><strong>{{ someText }}</strong></div>
<input type="text" #changes>
<button (click)="sendChanges(changes.value)">Send Changes</button>
</div>
Image Displaying Data Without Changes
https://i.sstatic.net/IukJr.png
Image Displaying Data With the Changes