【问题标题】:Angular 4 - Custom two way bindingAngular 4 - 自定义双向绑定
【发布时间】:2017-09-28 17:57:22
【问题描述】:

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

我确实读过有关命名约定的信息,说您必须定义一个 @Input() 像“test”,然后定义一个名为“testChange”的@Output()

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

parentComponent 中的一些代码:

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

我的组件(子):

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);
  }
}

父组件:

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);
    }
  }
}

我有什么遗漏吗? Angular 团队有什么改变吗?

Afaik 绑定做了类似的事情

[userGroupsIds]="userGroups" (userGroupsIdsChange)="userGroupIds=$event"

所以我尝试自己设置,但也没有更新。唯一可行的是将函数传递给 eventEmitter。

【问题讨论】:

  • ngOnChanges 仅在 @Input 中的任何一个发生更改时触发。我在您的父组件中看不到任何@Input。并且更改应该来自父组件(您的 parentComponent 的父组件)
  • 你有一个错字 - 额外的 d in userGroupdIdsChange

标签: html angular typescript


【解决方案1】:

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

来自Angular docs

OnChanges

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

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

【讨论】:

  • 天哪,我现在真的觉得自己很愚蠢。我什至没有想到 ngOnChanges 是这里的“问题”。谢谢!确实像一个魅力。编辑:还有其他可以做我期望 OnChanges 做的事情吗?
猜你喜欢
  • 2017-11-17
  • 1970-01-01
  • 1970-01-01
  • 2017-09-21
  • 2020-09-12
  • 2015-01-19
  • 1970-01-01
  • 2018-04-02
  • 1970-01-01
相关资源
最近更新 更多