问题
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 => {
// ...
});
}
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.
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)?
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.
回答1:
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); }
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.
})
}
}
来源:https://stackoverflow.com/questions/50724559/angular-how-to-make-ngcontrol-react-to-valuechanges-only-of-the-host-input