我正在查看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
答案 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
。