简体   繁体   English

Angular 4 - 自定义双向绑定

[英]Angular 4 - Custom two way binding

I am trying to implement a custom two way binding between two of my components. 我试图在我的两个组件之间实现自定义双向绑定。

I did read about the naming convention saying that you have to define a @Input() like " test " and then define a @Output() named " testChange ". 我确实读过有关命名约定的说法,你必须定义一个@Input()如“ test ”,然后定义一个名为“ testChange ”的@Output()

I couldn't find anything about whether this is still up-to-date or not and I can't get my binding to work. 我找不到任何关于这是否仍然是最新的,我无法让我的约束力工作。

Some code within parentComponent: parentComponent中的一些代码:

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

MyComponent (child): 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);
    }
  }
}

Is there something I am missing? 有什么我想念的吗? Did the Angular-Team change anything? Angular团队有什么改变吗?

Afaik the binding does something like Afaik绑定做的事情

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

So I tried setting this myself, but no update either. 所以我尝试自己设置,但也没有更新。 Only thing that work was passing a function to the eventEmitter. 只有工作才能将函数传递给eventEmitter。

Your binding works like a charm, it does not trigger the ngOnchanges method, which is the expected behavior. 你的绑定就像一个魅力,它不会触发ngOnchanges方法,这是预期的行为。

from the Angular docs : 来自Angular文档

OnChanges OnChanges

Lifecycle hook that is called when any data-bound property of a directive changes. 当指令的任何数据绑定属性更改时调用的生命周期钩子。

as userGroups is not an @Input() it cannot be a "data-bound property" , its value changing internally will not run the ngOnChanges hook. 由于userGroups不是@Input()因此它不能是“数据绑定属性”,其内部更改的值不会运行ngOnChanges挂钩。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM