NgModel binding is null in OnInit in Angular 2

I ran into a problem using Angular 2 ngModel binding. plnkr

If I use ngModel to bind a value to a child component, the value is not populated by the OnInit function of the child component. Therefore, if I bind to a call to the "boundName" property, and I try to access it in OnInit, it will be zero. However, if I bind to the same value in the parent control, not using ngModel, but an input parameter, the value is available in the OnInit function.

So if my parent component creates a child component like

 <my-boundcomp [(ngModel)]="name" [(inputName)] ="name" ></my-boundcomp>

And my onInit Function child components

public ngOnInit() {
   console.log("Input Name :" + this.inputName);
   console.log("Bound Name :" + this.boundName);
   this._boundNameOnInit = this.boundName; // <--- Going to be null
   this._inputNameOnInit = this.inputName; // <--- Going to be not null

}

. , , FormsModule ngModel, , , .

plnkr https://plnkr.co/edit/Im5oz7q1HhG5MgGTTZ1R?p=preview

+4
2

[(ngModel)]="name"

NgModel OnInit BoundValueComponent. BoundValueComponent.writeValue NgModel, boundName.

, .

+1

, "", , writeValue ControlValueAccessor. boundName , ngOnInit , writeValue .

(AfterViewInit, AfterContentInit), . , boundName, -, AfterViewInit AfterContentInit, writeValue.

writeValue. , . ...

export class BoundValueComponent  implements OnInit, ControlValueAccessor {

@Input() inputName: string;
boundName: string;

private _boundNameOnInit : string;
private _inputNameOnInit : string;

private initialized: boolean = false;

private onTouchedCallback: () => void = noop;
private onChangeCallback: (_: any) => void = noop;

constructor() {
}

public ngOnInit() {
   console.log("Input Name :" + this.inputName);
   console.log("Bound Name :" + this.boundName);
  // this._boundNameOnInit = this.boundName; // <--- Going to be null
   this._inputNameOnInit = this.inputName; // <--- Going to be not null
}

get value(): any {
  return this.boundName;
};

/**
* Set accessor including call the onchange callback.
*/
set value(v: any) {
  if (v !== this.boundName) {
     this.boundName = v;
     this.onChangeCallback(v);
  }
}

/**
* From ControlValueAccessor interface.
*/
writeValue(value: any) {
 this.boundName = value;

 if (!this.initialized) {
   this._boundNameOnInit = this.boundName;
   this.initialized = true;
 }
}
.......
+1

Source: https://habr.com/ru/post/1656600/


All Articles