Angular 9-数组类型输入属性在两个组件上都改变了?

问题描述 投票:0回答:1

我遇到了一个我想确保是真的问题。我写了一个小的Angular应用程序来展示我在说什么。

当我将Array(any []或Object [])作为@Input属性传递给子组件并更改Child中的值时,为什么更改会反映在Parent中?从我从文档中读取的内容来看,这应该是单向绑定,这意味着我将不得不从子级使用@Output属性(EventEmitter)将更改发送回父级。

我提供的代码作为我正在解释的示例,也许范围太广。该代码具有两个要发送给子组件的属性,一个是对象数组,另一个是纯文本字符串。我正在使用输入字段来更改Name1的值和纯文本值。

所以我的问题是,为什么当我对数据数组进行更改时,这些更改会反映在父级中,但是当我更改文本字符串时却没有?文档中是否有解释的地方,或者有人可以解释为什么?

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

图像显示数据具有更改

Image Displaying Data With the Changes

angular typescript
1个回答
0
投票

这与javaScript / typeScript有关,而不与Angular相关>

对象和数组是通过引用传递的,因此,如果您在某个地方更新了数组,它将在其他地方更新

您可以传递数组的副本,而不是传递数组本身

我们可以使用类似的方法从对象或数组中获取副本

let snapshotOfMyArray = JSON.parse(JSON.stringify(myArray));

所以我们可以在应用程序组件模板中做到这一点

<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]="JSON.parse(JSON.stringify(arr))" [someText]="someText"></child-component>
© www.soinside.com 2019 - 2024. All rights reserved.