Angular:如何让 NgControl 仅对主机的 valueChanges 做出反应 <input> [英] Angular: how to make NgControl react to valueChanges only of the host <input>

查看:25
本文介绍了Angular:如何让 NgControl 仅对主机的 valueChanges 做出反应 <input>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 <input> 元素上使用指令并获得对其控件的引用,如下所示:

I am using a directive on an <input>-element and get a reference to its controls like this:

@ContentChild(NgControl) private readonly _inputNgControl: NgControl;

但是当我像这样听模型更改时:

But when I listen to model-changes like so:

  ngAfterContentInit(): void {
    this._inputNgControl.control.valueChanges
      .distinctUntilChanged()
      .subscribe(value => {
         // ...
    });
  }

看来 this._inputNgControl.control 不是指指令所在的输入,而是指我父组件中的所有输入(其中包含多个 -elements 具有相同的指令),因为我从父级中的所有这些输入中获得更改,而不仅仅是我输入的内容.

it appears that this._inputNgControl.control refers not to the input that the directive is sitting on, but to ALL inputs in my parent component (which contains multiple <input>-elements with the same directive) because I get changes from all of those inputs in the parent and not only the one where I typed something.

那么我怎样才能过滤仅活动输入的 valueChange 呢?我是否需要使用构造函数来注入它,这会使 NgControl 成为本地而不是全局吗?或者我是否需要自己使用 forwardRef 实现 VALUE_ACCESSOR(据我所知,这是 NgControl 正在做的事情)?

So how can I filter the valueChange's of only the active input? Do I need to use the constructor to inject it, will that make the NgControl local instead of global? Or do I need to implement VALUE_ACCESSOR myself with forwardRef (which is what NgControl is doing as far as I understand it)?

最不干净的解决方案是将 id 传递给指令并 make

The least clean solution would be passing an id to the directive and make

.filter(() => this._directiveId === this._inputNgControl.name)

所以我想尽可能避免这种情况.

so I want to avoid that if possible.

推荐答案

使用 HostListener 很有帮助.到目前为止,我一直在使用 HostListener 来处理本机浏览器事件,例如监听键盘操作或鼠标滚动,但我不知道您可以使用它们来访问主机元素的输出(因此名称主机监听器,duh!) 还有:

What helped was to use HostListener. I have been using HostListener so far only to handle native browser events, like listening to keyboard actions or mouse scrolling, but I had no idea you can use them to get access to the outputs of the host element (thus the name host listener, duh!) as well:

@HostListener('ngModelChange', ['$event'])
onModelChange(value: string | number) { this.modelChange$.next(value); }

然后在带有 ContentChild 的组件中:

And then in the component with the ContentChild:

@Component({
  selector: input-wrapper',
  template: `<ng-content></ng-content>`
})
export class InputWrapperComponent implements AfterContentInit {
  @ContentChild(InputControllerDirective) private _icd: InputControllerDirective;

  ngAfterContentInit() {
    this._icd.modelChange$.subscribe((value: string | number) => {
       // do sth.
    })
  }
}

这篇关于Angular:如何让 NgControl 仅对主机的 valueChanges 做出反应 &lt;input&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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