【问题标题】:How does NgModel work internally (set value initially)NgModel 内部如何工作(初始设置值)
【发布时间】:2017-06-18 04:49:01
【问题描述】:

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

NgModel extends NgControl

..

NgControl extends NgControlDirective

..

NgControlDirective 有这个代码:

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

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

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

它如何知道初始设置值。

我猜它与

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

【问题讨论】:

  • But this.control.setValue is done only on update in NgModel.第一次调用ngOnChanges会通知第一次更新。
  • 我也观察到,看起来是合法的。SimpleChanges 甚至有一个布尔值来告诉它的第一次更新。但不完全确定它是否正确
  • 那是正确的,你能发布一个答案吗?

标签: angular angular2-ngmodel


【解决方案1】:

假设我们有以下模板

<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 将被调用的位置。

【讨论】:

    猜你喜欢
    • 2019-12-18
    • 1970-01-01
    • 2023-01-30
    • 2017-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    相关资源
    最近更新 更多