NgModel如何在内部工作(最初设置值)

时间:2017-06-18 04:49:02

标签: angular angular2-ngmodel

我正在查看NgModel的源代码。我理解它的大部分内容,除了它如何设置输入的初始value

NgModel extends NgControl

...

NgControl extends NgControlDirective

...

NgControlDirective有以下代码:

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

因此,如果我们设置this.control.value,它会自动设置为value的{​​{1}}。好。

input仅在this.control.setValue更新时完成。

如何知道最初设置值。

我猜它与

有关
NgModel

1 个答案:

答案 0 :(得分:3)

假设我们有以下模板

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

并在组件类

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

enter image description here