我正在尝试实现我的两个组件之间的自定义双向绑定。
我确实读过关于命名约定的文章,其中说您必须定义一个@Input(),比如"test“,然后定义一个名为"testChange”的@Output()。
我没有找到任何关于这是否仍然是最新的,我无法使我的绑定工作。
parentComponent中的一些代码:
<my-comp [(userGroupIds)]="userGroups"></my-comp>
MyComponent (儿童):
export class MyComponent implements OnInit, OnDestroy{
@Input() userGroupIds: number[];
@Output() userGroupIdsChange = new EventEmitter<number[]>();
updateValues(){
//here I am iterating through the rows of a table within my component
this.userGroupIds = this.tableRows.map(item => {return item['id']});
this.userGroupdIdsChange.emit(this.userGroupIds);
}
}parentComponent:
export class parentComponent implements OnInit, OnChanges, OnDestry{
userGroups: number[];
constructor(){
this.userGroups = [];
}
ngOnChanges(changes: SimpleChanges){
if(changes['userGroups']){
// this is never show, ngOnChanges doesn't get fired;
console.log(this.userGroups);
}
}
}我遗漏了什么吗?角队里有什么变化吗?
Afaik绑定的功能类似于
[userGroupsIds]="userGroups" (userGroupsIdsChange)="userGroupIds=$event"所以我试着自己设置,但也没有更新。唯一能做的就是把一个函数传递给eventEmitter。
发布于 2017-09-28 09:15:06
您的绑定就像一个魅力,它不触发ngOnchanges方法,这是预期的行为。
来自角文档:
OnChanges 当指令的任何数据绑定属性更改时调用的生命周期挂钩。
由于userGroups不是一个@Input() --它不能是一个“数据绑定属性”,它的值在内部的变化将不会运行ngOnChanges挂钩。
https://stackoverflow.com/questions/46465222
复制相似问题