What could be the issue, for example we have two list:

Parent component:

@Component({
selector: 'passenger-dashboard',
styleUrls: ['passenger-dashboard.component.scss'],
template: `
<div>
<passenger-count
[items]="passengers">
</passenger-count>
<div *ngFor="let passenger of passengers;">
{{ passenger.fullname }}
</div>
<passenger-detail
*ngFor="let passenger of passengers;"
[detail]="passenger"
(edit)="handleEdit($event)"
(remove)="handleRemove($event)">
</passenger-detail>
</div>
`
})
export class PassengerDashboardComponent implements OnInit {
passengers: Passenger[];
constructor() {}
ngOnInit() {
this.passengers = [{
id: ,
fullname: 'Stephen',
checkedIn: true,
checkInDate: ,
children: null
}, {
id: ,
fullname: 'Rose',
checkedIn: false,
checkInDate: null,
children: [{ name: 'Ted', age: },{ name: 'Chloe', age: }]
}, {
id: ,
fullname: 'James',
checkedIn: true,
checkInDate: ,
children: null
}, {
id: ,
fullname: 'Louise',
checkedIn: true,
checkInDate: ,
children: [{ name: 'Jessica', age: }]
}, {
id: ,
fullname: 'Tina',
checkedIn: false,
checkInDate: null,
children: null
}];
}
handleEdit(event: Passenger) {
this.passengers = this.passengers.map((passenger: Passenger) => {
if (passenger.id === event.id) {
passenger = Object.assign({}, passenger, event);
}
return passenger;
});
}
handleRemove(event: Passenger) {
this.passengers = this.passengers.filter((passenger: Passenger) => {
return passenger.id !== event.id;
});
}
}

Child component:

@Component({
selector: 'passenger-detail',
styleUrls: ['passenger-detail.component.scss'],
template: `
<div>
<span class="status" [class.checked-in]="detail.checkedIn"></span>
<div *ngIf="editing">
<input
type="text"
[value]="detail.fullname"
(input)="onNameChange(name.value)"
#name>
</div>
<div *ngIf="!editing">
{{ detail.fullname }}
</div>
<div class="date">
Check in date:
{{ detail.checkInDate ? (detail.checkInDate | date: 'yMMMMd' | uppercase) : 'Not checked in' }}
</div>
<div class="children">
Children: {{ detail.children?.length || }}
</div>
<button (click)="toggleEdit()">
{{ editing ? 'Done' : 'Edit' }}
</button>
<button (click)="onRemove()">
Remove
</button>
</div>
`
})
export class PassengerDetailComponent implements OnInit { @Input()
detail: Passenger; @Output()
edit: EventEmitter<any> = new EventEmitter(); @Output()
remove: EventEmitter<any> = new EventEmitter(); editing: boolean = false; constructor() {} ngOnInit() {
console.log('ngOnInit');
} onNameChange(value: string) {
this.detail.fullname = value;
} toggleEdit() {
if (this.editing) {
this.edit.emit(this.detail);
}
this.editing = !this.editing;
}
onRemove() {
this.remove.emit(this.detail);
}
}

They both display list of "passengers".

What will happens that when we change the "passenger" value in 'passenger-detail' component. It will using '(edit)' event to update parent component's 'passengers' variable.

Both changes happens in the same time.

But what we really want is, until child component click "Done" button then parent component get udpate.

So what we can do is using 'ngOnChanges' in child component to break Javascript object reference (this.detail, which marked in yellow background).

export class PassengerDetailComponent implements OnChanges, OnInit {

  constructor() {}

  ngOnChanges(changes) {
if (changes.detail) {
this.detail = Object.assign({}, changes.detail.currentValue);
}
console.log('ngOnChanges');
} onNameChange(value: string) {
this.detail.fullname = value;
} ...
}

We use 'Object.assign' to create a new 'this.detail' object reference.

And because of this new creation, it actually breaks the reference of 'this.detail'.

And only when click "Done" button, the deatial will be sent to the parent component.

[Angular] Using ngOnChanges lifeCycle hook to break object reference的更多相关文章

  1. [React] Update State Based on Props using the Lifecycle Hook getDerivedStateFromProps in React16.3

    getDerivedStateFromProps is lifecycle hook introduced with React 16.3 and intended as a replacement ...

  2. [React] Capture values using the lifecycle hook getSnapshotBeforeUpdate in React 16.3

    getSnapshotBeforeUpdate is a lifecycle hook that was introduced with React 16.3. It is invoked right ...

  3. [MST] Loading Data from the Server using lifecycle hook

    Let's stop hardcoding our initial state and fetch it from the server instead. In this lesson you wil ...

  4. ArcGIS AddIN异常之:object reference not set to an instance of an object

    异常出现在 frmDownload frd = new frmDownload(); frd.ShowDialog(); 在ArcMap中能正常弹出窗体,点击按钮时显示此异常:object refer ...

  5. Java中对不变的 data和object reference 使用 final

    Java中对不变的 data和object reference 使用 final 许多语言都提供常量数据的概念,用来表示那些既不会改变也不能改变的数据,java关键词final用来表示常量数据.例如: ...

  6. Attempt to write to field 'android.support.v4.app.FragmentManagerImpl android.support.v4.app.Fragment.mFragmentManager' on a null object reference

    E/AndroidRuntime﹕ FATAL EXCEPTION: mainProcess: org.example.magnusluca.drawertestapp, PID: 3624java. ...

  7. Azure Sphere–“Object reference not set to an instance of an object” 解决办法

    在开发Azure Sphere应用时,如果出现项目无法编译,出现“Object reference not set to an instance of an object”时,必须从下面两个方面进行检 ...

  8. Visual Studio 2015打开ASP.NET MVC的View提示"Object reference not set to an instance of an object"错误的解决方案

    使用Visual Studio 2013打开没有问题,但Visual Studio 2015打开cshtml就会提示"Object reference not set to an insta ...

  9. Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayShowHomeEnabled(boolean)' on a null object reference

    /********************************************************************************* * Caused by: java ...

随机推荐

  1. SpringBoot+springmvc异步处理请求

    有两种情况,第一种是业务逻辑复杂,但不需要业务逻辑的结果,第二种是需要返回业务逻辑的处理结果 第一种比较简单,利用多线程处理业务逻辑,或者利用spring中@Asyn注解更简单, 使用@Asyn注解, ...

  2. [Node & Testing] Intergration Testing with Node Express

    We have express app: import _ from 'lodash' import faker from 'faker' import express from 'express' ...

  3. OrmLite使用小结(一)

    在使用OrmLite过程中,遇到了不少问题.鉴于中文文档比較少,看英文文档又不知道怎样看起.仅仅能遇到问题查找解决方法并整理出来,如有错误,希望能指正! ** 1.模糊条件查询 ** 使用条件查询时. ...

  4. CentOS卸载Apache方法

    https://www.kafan.cn/edu/49420412.html CentOS卸载Apache方法 首先关闭httpd服务 /etc/init.d/httpd stop 列出httpd相关 ...

  5. 4lession-输入函数

    接受字符串的方法 #!/usr/bin/python string = raw_input("\nplease inter you string:\n") print(string ...

  6. android中常见声音操作方式(Ringtone,SoundPool,MediaPlayer)小结

    在Android开发中有时候需要用到播放声音操作,在android API 的media包中有三种方式可供我们选择,它们分别是Ringtone,SoundPool,MediaPlayer.因为在我目前 ...

  7. 【Codeforces Round #446 (Div. 2) B】Wrath

    [链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 倒着来,维护一个最小的点就可以了. [代码] #include <bits/stdc++.h> using namesp ...

  8. valueof(), intvalue(0 parseint() 这三个方法怎么用

    valueOf(int i) 返回一个表示指定的 int 值的 Integer 实例.valueOf(String s) 返回保存指定的 String 的值的 Integer 对象.valueOf(S ...

  9. android问题及其解决-优化listView卡顿和怎样禁用ListView的fling

    问题解决-优化listView卡顿和怎样禁用ListView的fling 前戏非常长,转载请保留出处:http://blog.csdn.net/u012123160/article/details/4 ...

  10. HTTP网络协议(二)

    HTTP报文内的HTTP信息 HTTP协议交互的信息被称为HTTP报文,请求端的HTTP报文叫做请求报文,响应端的叫做响应报文.    HTTP为了提升传输速率,其在传输数据时,按照数据原样进行压缩传 ...