NgModel 内部是如何工作的(初始设置值)

How does NgModel work internally (set value initially)

我在看NgModel的源代码。除了如何设置输入的初始 value 之外,我了解其中的大部分内容。

NgModel extends NgControl

..

NgControl extends NgControlDirective

..

NgControlDirective 有这个代码:

get value(): any { return this.control ? this.control.value : null; }

因此,如果我们设置 this.control.value,它会自动设置为 value of input。好的。

但是 this.control.setValue 仅在 NgModel 中更新时完成。

它是怎么知道初始设置值的。

我猜它与

有关
this.valueAccessor = selectValueAccessor(this, valueAccessors);

假设我们有以下模板

<input type="text" [ngModel]="x">

并在组件 class

x = 3;

当根据 life cycles hooks documentation 初始化指令时 ngOnChange 钩子被调用 currentValue 3

ngOnChanges(changes: SimpleChanges) {
  this._checkForErrors();
  if (!this._registered) this._setUpControl();
  if ('isDisabled' in changes) {
    this._updateDisabled(changes);
  }

  if (isPropertyUpdated(changes, this.viewModel)) {
    this._updateValue(this.model);
    this.viewModel = this.model;
  }
}

因为 previousValue 等于 undefined this._updateValue(this.model); 方法将被调用。

private _updateValue(value: any): void {
  resolvedPromise.then(
      () => { this.control.setValue(value, {emitViewToModelChange: false}); });
}

其中 this.control.setValue 将被调用。