代码之家  ›  专栏  ›  技术社区  ›  Phil

角度:如何使ngcontrol仅对主机的值更改做出反应<input>

  •  1
  • Phil  · 技术社区  · 8 年前

    我在用一个指令 <input> -元素并获取对其控件的引用,如下所示:

    @ContentChild(NgControl) private readonly _inputNgControl: NgControl;
    

    但当我听到模型的变化时:

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

    看来 this._inputNgControl.control 不是指指令所在的输入,而是指父组件中的所有输入(包含多个 <输入& GT; -元素与相同的指令),因为我从父元素中的所有这些输入获取更改,而不仅仅是从我键入内容的输入获取更改。

    那么,如何过滤只有活动输入的valuechange呢?我是否需要使用构造函数来注入它,这会使ngcontrol成为本地的而不是全局的吗?或者我需要用forwardref实现值访问器(据我所知,ngcontrol正在做什么)?

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

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

    所以如果可能的话我想避免。

    1 回复  |  直到 8 年前
        1
  •  0
  •   Phil    8 年前

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

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

    然后在包含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.
        })
      }
    }
    
    推荐文章