【问题标题】:Use [(ngModel)] to change only the reference object, not the source使用 [(ngModel)] 仅更改引用对象,而不更改源
【发布时间】:2021-09-25 12:46:17
【问题描述】:

我正在使用Angular 12.0.4

我的模板有这样的输入:

<input type="text" [(ngModel)]="end.itemOne">
<button (click)="resetField()">reset</button>


<p>why does <strong style="color:red">this.start</strong> change with input value? </p>
<strong>{{ this.start.itemOne }}</strong>
<br>
<br>
<p>I need only <strong style="color:blue">this.end</strong> to change </p>
<strong>{{ this.end.itemOne }}</strong>

组件内部:

start: any = {
    itemOne: 'item1',
    itemTwo: 'item2'
  };

  end!: any;

  ngOnInit(): void {
    this.end = this.start;
  }

  resetField(): void {
    this.end = this.start;
  }

这是一个 stackblitz 显示问题: https://stackblitz.com/edit/angular-njppqj?file=src%2Fapp%2Fapp.component.ts

我的问题是:如果我更改输入值然后单击reset button 我希望this.end.itemOne 值再次变为“item1”。相反,当我更改输入值时,this.startthis.end 的值将相等。

提前致谢。

【问题讨论】:

  • ngOnInit(){this.resetField();}resetField():void{ this.end = {...this.start}}。重点是创建对象的副本并将其放入末尾。在您的情况下,开始和结束引用相同的“内存速度”
  • 感谢您的回复,但我该如何避免这种行为?
  • @gustavo-branco 默认情况下,对象分配是引用类型,您需要失去对我在回答中提到的一些选项的引用

标签: angular


【解决方案1】:

您正在寻找的方式是copy an object and lose its reference。所以你有multiple option 来实现它。

最简单的方法是扩展符号:

this.end = {... this.start};

另一种方式是Object.assign

对于嵌套对象,您甚至可以使用:

<YourObjType> JSON.parse(JSON.stringify(originalObject));

https://stackblitz.com/edit/angular-sftvoi?file=src%2Fapp%2Fapp.component.ts

【讨论】:

  • 我从没见过这个,谢谢!我使用了这种“传播符号”的方式。
  • “扩展符号方式”仅在第一次运行重置功能时有效,第二次按下按钮,原来的问题又回来了。使用 JSON.parse 解决了这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-30
  • 2016-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-14
  • 1970-01-01
相关资源
最近更新 更多