How does NgModel work internally (set value initially)


I am looking at the source code of NgModel. I understand most part of it except that how is it setting the initial value of input.

NgModel extends NgControl


NgControl extends NgControlDirective


NgControlDirective has this code:

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

So if we set this.control.value it automatically sets to value of input. Good.

But this.control.setValue is done only on update in NgModel.

how does it know to set the value initially.

I guess its something related to

this.valueAccessor = selectValueAccessor(this, valueAccessors);


Let’s say we have the following template

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

and in component class

x = 3;

When directive is initialized according to life cycles hooks documentation ngOnChange hook is called with currentValue 3

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

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

Since previousValue equals undefined this._updateValue(this.model); method will be called.

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

where this.control.setValue will be called.

enter image description here

Answered By – yurzui

Answer Checked By – Gilberto Lyons (AngularFixing Admin)

Leave a Reply

Your email address will not be published.