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. echarts统计图踩坑合集

    1:折线图条的颜色修改 series : [ { name : 'SBP(收缩压)', type : 'line', itemStyle : { normal : { lineStyle:{ colo ...

  2. CISP/CISA 每日一题 21

    CISSP 每日一题(答)What is the term that identifies data ona disk after the data has supposedly been erase ...

  3. 感谢党,软考过了。系统集成项目管理project师

    人品爆发了,刚用干巴巴的日语做完2小时的设计说明,回到家一查,人品爆发了.软考竟然过了. 绝对是评卷老师给人品啊!真想请他吃顿饭. 系统集成项目管理project师  64 53 幸运飞过! 今天真是 ...

  4. Cocos2d-x学习笔记(三)CCNode分析

    原创文章.转载请注明出处:http://blog.csdn.net/sfh366958228/article/details/38706483 通过前两份学习笔记,我们不难发现CCScene.CCLa ...

  5. Android 使用Wake Lock

    为了延长电池的使用寿命,Android设备会在一段时间后使屏幕变暗,然后关闭屏幕显示,最后停止CPU.WakeLock是一个电源管理系统服务功能,应用程序可以使用它来控制设备的电源状态. WakeLo ...

  6. PHP服务器环境打开配置文件

    MAC 1.  cd /usr/local/etc/nginx/servers vim www.xxx.com 2. 在/usr/local/etc/nginx/servers目录下,不同的 .con ...

  7. json问题小结

    json 键值对增加.删除 obj.key='value'; // obj.key=obj[key]=eval("obj."+key); delete obj.key; vue中新 ...

  8. The Swift Programming Language 中文翻译版

    原文(http://www.cnblogs.com/lkvt/p/3765349.html) 一.Welcome to Swift 1.关于Swift Swift是一种用于iOS和OS X应用的全新编 ...

  9. js进阶 13-7 如何实现滑动面板效果

    js进阶 13-7 如何实现滑动面板效果 一.总结 一句话总结:就是普通的jquery动画中的滑动效果.$('#content').slideToggle().滑动效果的实质是通过调整高度. 1.滑动 ...

  10. Project Euler 516 5-smooth totients (数论)

    题目链接: https://projecteuler.net/problem=516 题目: \(5\)-smooth numbers are numbers whose largest prime ...