[Angular] Using ngOnChanges lifeCycle hook to break object reference
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的更多相关文章
- [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 ...
- [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 ...
- [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 ...
- ArcGIS AddIN异常之:object reference not set to an instance of an object
异常出现在 frmDownload frd = new frmDownload(); frd.ShowDialog(); 在ArcMap中能正常弹出窗体,点击按钮时显示此异常:object refer ...
- Java中对不变的 data和object reference 使用 final
Java中对不变的 data和object reference 使用 final 许多语言都提供常量数据的概念,用来表示那些既不会改变也不能改变的数据,java关键词final用来表示常量数据.例如: ...
- 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. ...
- Azure Sphere–“Object reference not set to an instance of an object” 解决办法
在开发Azure Sphere应用时,如果出现项目无法编译,出现“Object reference not set to an instance of an object”时,必须从下面两个方面进行检 ...
- 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 ...
- Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayShowHomeEnabled(boolean)' on a null object reference
/********************************************************************************* * Caused by: java ...
随机推荐
- 初学WCF需要注意的地方
1.WCF的元数据发布有两种方式: a.HTTP-GET方式发布数据:让客户端使用HTTP-GET方式来获取数据是比较常见的方式.所谓HTTP—GET方式,是指当客户端发送一个HTTP-GET请求时, ...
- 【Educational Codeforces Round 35 C】Two Cakes
[链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 直觉题. 感觉情况会很少. 毕竟间隔太大了.中间肯定有一些数字达不到. 有1肯定可以 2 2 x肯定可以 3 3 3也可以 2 4 ...
- eclipse git冲突解决
1.工程->Team->同步: 2.从远程pull至本地,就会出现如下内容: 3.使用Merge Tool,执行第二项 4.再手动修改 4.修改后的文件需要添加到Git index中去: ...
- mIsFunui-判断Funui方法
1.有时候我们根据自己的需要,修改了frameword下的代码,但是,我们又不希望影响第三方,这时候我们就可以在修改处添加一个我们自己的标志位,如,mIsFunui 它是定义在我们自定义的theme里 ...
- Xamarin开发手机聊天程序
使用Xamarin开发手机聊天程序 -- 基础篇(大量图文讲解 step by step,附源码下载) 如果是.NET开发人员,想学习手机应用开发(Android和iOS),Xamarin 无疑是 ...
- php编译参数注释
1. 指定安装路径 --prefix=PREFIX 2. 指定运行用户 --with-fpm-user=nginx 3. 指定运行组 --with-fpm-group=nginx 3.与'--pref ...
- docker网络访问
一 docker网络访问 描述: 在启动容器的时候,如果不指定对应的参数,在容器外部是无法通过网络来访问容器内的网络应用和服务的.当容器中运行一些网络应用,要让外部访问这些应用时,可以通过-P或者-p ...
- ORACLE10g R2【RAC+ASM→RAC+ASM】
ORACLE10g R2[RAC+ASM→RAC+ASM] 本演示案例所用环境:RAC+ASM+OMF primary standby OS Hostname node1,node2 dgnode ...
- html实现返回上一页的几种方法(javaScript:history.go(-1);)
html实现返回上一页的几种方法(javaScript:history.go(-1);) 一.总结: 1.javaScript:history.go(-1); 二.方法 1.通过超链接返回到上一页 & ...
- (转)利用openfiler实现iSCSI
转自:http://czmmiao.iteye.com/blog/1735417 openfiler openfiler是一个基于浏览器的网络存储管理工具.来自于Linux系统.openfiler在一 ...