[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 ...
随机推荐
- BZOJ3192: [JLOI2013]删除物品(splay)
Description 箱子再分配问题需要解决如下问题: (1)一共有N个物品,堆成M堆. (2)所有物品都是一样的,但是它们有不同的优先级. (3)你只能够移动某堆中位于顶端的物品. ( ...
- ASP.Net MVC Filter验证用户登录
一.Filter是什么 ASP.NetMVC模式自带的过滤器Filter,是一种声明式编程方式,支持四种过滤器类型,各自是:Authorization(授权),Action(行为),Result(结果 ...
- Hibernate3.5.4---java application的xml和annotation环境搭建(hibernate.cfg.xml配置文件说明,映射文件Student.hbm.xml说明
http://blog.csdn.net/centre10/article/details/6050466 来自于:http://blog.csdn.net/centre10/article/deta ...
- 洛谷——P1548 棋盘问题
https://www.luogu.org/problem/show?pid=1548#sub 题目描述 设有一个N*M方格的棋盘(l<=N<=100,1<=M<=100)(3 ...
- logback--How do I configure an AsyncAppender with code? 转载
原文地址:https://github.com/tony19/logback-android/issues/54 Please provide an example of how to configu ...
- jmeter--元件的作用域与执行顺序
1.元件的作用域 JMeter中共有8类可被执行的元件(测试计划与线程组不属于元件),这些元件中,取样器是典型的不与其它元件发生交互作用的元件,逻辑控制器只对其子节点的取样器有效,而其它元件(conf ...
- BigBoss按键映射
// BigBoss: SBSettings Toggle Spec 按键映射 http://thebigboss.org/guides-iphone-ipod-ipad/sbsettings-tog ...
- 防止 Chrome 屏蔽 非官方 扩展程序 教程(一)
说明 Google Chrome,又称 Google 浏览器,是一个由 Google(谷歌)公司开发的网页浏览器.该浏览器是基于其它开源软件所撰写.包含 WebKit,目标是提升稳定性.速度和安全性. ...
- Static关键字深入理解
1.static变量 按照是否静态的对类成员变量进行分类可分两种:一种是被static修饰的变量,叫静态变量或类变量:另一种是没有被static修饰的变量,叫实例变量. 两者的区别是: 对于静态变量在 ...
- linux的关机
shutdown -h now 立即关机 shutdown -r now 立即重启