Angular2+:NgModel / NgControl如何在内部处理从视图到模型的更新?



我正在深入研究双向数据绑定的工作原理。我目前对视图(例如,input元素(的更新如何在内部传播到NgControl感到困惑。

ControlValueAccessor的定义中,它提到registerOnChange负责视图>模型更新(他们说的文档和src(。通过一个简单的指令,我们可以放在与[(NgModel)]相同的input元素上,例如<input [(NgModel)]=stuff myInspectorDirective>,我试着玩这个。

constructor(private ngControl: NgControl) { }
ngOnInit(): void {
// this.ngControl.valueAccessor['onChange'] = () => {}; 
// uncommenting the above line prevents updates from view to model 
}

取消注释/注释指示的行允许我们允许/阻止从输入元素到模型的更新。但我对此感到困惑,因为在 DefaultValueAccessor 的源代码中,在这个例子中使用的源代码中,onChange并没有真正做任何事情:(_:any) => {}

所以,我希望在引擎盖下,例如在 ng_model.ts 或相关类之一中,如NgControlFormControl中,来自 ValueAccessor 的onChange函数会发生一些事情; 设置它或将其包装在另一个函数中,也许是代理,或者其他什么。我什么也没找到。然后我继续寻找一些代码,其中侦听器(对于input事件,更明确地(显式绑定到输入元素,但也没有运气。

我注意到OnChanges函数调用_setValue,但我不确定在深入研究更改检测的内部时我是否朝着正确的方向前进,因为我希望侦听 DOM 中的更改与ControlValueAccessors和/或FormControl/AbstractControl

有人想详细说明这是如何工作的吗?:-(

ControlValueAccessor.registerOnChange 由 NgForm 提供。

1( NgModel 在 NgForm 中注册(见 https://github.com/angular/angular/blob/master/packages/forms/src/directives/ng_model.ts(

in NgModel.ngOnChanges: this._setUpControl calls this.formDirective.addControl

2( NgForm 调用共享设置控制函数(见 https://github.com/angular/angular/blob/master/packages/forms/src/directives/ng_form.ts(

import { setUpControl } from './shared';
NgForm.addControl calls setUpControl

3( setUpControl 寄存器更改事件处理程序(见 https://github.com/angular/angular/blob/master/packages/forms/src/directives/shared.ts(

setUpControl calls setUpViewChangePipeline
function setUpViewChangePipeline(control: FormControl, dir: NgControl): void {
dir.valueAccessor !.registerOnChange((newValue: any) => {
control._pendingValue = newValue;
control._pendingChange = true;
control._pendingDirty = true;
if (control.updateOn === 'change') updateControl(control, dir);
});
}

最新更新