首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角4-自定义双向绑定

角4-自定义双向绑定
EN

Stack Overflow用户
提问于 2017-09-28 09:06:30
回答 1查看 3K关注 0票数 4

我正在尝试实现我的两个组件之间的自定义双向绑定。

我确实读过关于命名约定的文章,其中说您必须定义一个@Input(),比如"test“,然后定义一个名为"testChange”的@Output()

我没有找到任何关于这是否仍然是最新的,我无法使我的绑定工作。

parentComponent中的一些代码:

<my-comp [(userGroupIds)]="userGroups"></my-comp>

MyComponent (儿童):

代码语言:javascript
复制
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:

代码语言:javascript
复制
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绑定的功能类似于

代码语言:javascript
复制
[userGroupsIds]="userGroups" (userGroupsIdsChange)="userGroupIds=$event"

所以我试着自己设置,但也没有更新。唯一能做的就是把一个函数传递给eventEmitter。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-09-28 09:15:06

您的绑定就像一个魅力,它不触发ngOnchanges方法,这是预期的行为。

来自角文档

OnChanges 当指令的任何数据绑定属性更改时调用的生命周期挂钩。

由于userGroups不是一个@Input() --它不能是一个“数据绑定属性”,它的值在内部的变化将不会运行ngOnChanges挂钩。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46465222

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档