角度双向数据绑定和监视父组件中的更改 [英] Angular Two-Way Data Binding and Watching for Changes in Parent Component

查看:89
本文介绍了角度双向数据绑定和监视父组件中的更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用双向数据绑定时,似乎无法观察父组件中的更改.

It seems there is no way to watch changes in the parent component when using two-way data binding.

我有一个用于收集标签列表的自定义输入组件.在此组件与其父组件之间建立了双向数据绑定,并可以使用该双向数据绑定.

I have a custom input component for collecting a tag list. Two-way data binding is setup and working between this component and its parent.

// the parent component is just a form
// here is how I'm adding the child component
<input-tags formControlName="skillField" [(tags)]='skillTags' (ngModelChange)="skillTagUpdate($event)"></input-tags>

在父组件中,如何查看绑定变量的更改?尽管它始终是最新的(我已经确认了这一点),但我找不到任何对更改做出反应的指导.

In the parent component how do you watch the bound variable for changes? While it's always up to date (I've confirmed this) I cannot find any guidance on reacting to changes.

我尝试过:

ngOnChanges(changes: SimpleChanges) {
    if (changes['skillTags']) {
        console.log(this.skillTags);  // nothing
    }
}

skillTagUpdate(event){
    console.log(event); // nothing
}

更新: TWDB恕我直言,它不是广告.每当我到达TWDB似乎是解决方案的地方时,我都会重新选择服务和/或可观察的通信.

UPDATE: TWDB IMHO is not what it is advertised to be. Whenever I arrive at this place where TWDB seems to be a solution I rearchitect for a service and or observable communication instead.

推荐答案

当实现自己的双向绑定时,必须实现事件Emitter.语法是强制性的.

When you implement a two way binding of your own, you have to implement an event Emitter. The syntax for that is mandatory.

这意味着如果值更改,您有一个钩子可以收听.

this means that you have a hook to listen to if the value changes.

这是一个演示:

<hello [(name)]="name" (nameChange)="doSomething()"></hello>

_name: string;
@Output() nameChange = new EventEmitter();

set name(val) {
  this._name = val;
  this.nameChange.emit(this._name);
}

@Input()
get name() {
  return this._name;
}

counter = 0;

ngOnInit() {
  setInterval(() => {
    this.name = this.name + ', ' + this.counter++;
  }, 1000);
}

Stackblitz

据我所知,这似乎是使用它的较不烦人的方法,无论如何,任何两种方式的绑定都将遵循相同的规则,即它以Change单词结尾!

From what I know, this seems the less annoying way to use it, and any two way binding will follow the same rule no matter what, i.e. it ends with the Change word !

这篇关于角度双向数据绑定和监视父组件中的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆