angular 6 deprecation of using formControlName and ngModel together

realist picture realist · Oct 4, 2018 · Viewed 12.9k times · Source

I have angular 6 project. And I was using ngModel and formControlName together. But angular gave me warning in below. Forexamle when I open update popup from button in grid, I can easily bind inputs in update popup automatically. But angular 7 says that remove ngModel. So, I must always map everything to my student object. What is the best way for this? Can we give formValueType to form value like studentObject in below code and then can it bind automatically?

Angular warning:

     It looks like you're using ngModel on the same form field 
as formControlName. Support for using the ngModel input property and 
ngModelChange event with reactive form directives has been deprecated
 in Angular v6 and will be removed in Angular v7.

myHtml

<form [formGroup]="studentForm" ??????formValueType="studentObject"?????>
  <p-dialog>
    <div class="ui-g-12 form-group">
      <div class="ui-g-4">
        <label>Name Surname</label>
      </div>
      <div class="ui-g-8">
        <input pInputText [(ngModel)]="selectedStudent.nameSurname"  formControlName="nameSurname" />
      </div>
    </div>
    <div class="ui-g-12 form-group">
      <div class="ui-g-4">
        <label>Email</label>
      </div>
      <div class="ui-g-8">
        <input pInputText [(ngModel)]="selectedStudent.email" formControlName="email" />
      </div>
    </div>
        <div class="ui-g-12 form-group">
          <div class="ui-g-4">
            <label>Age</label>
          </div>
          <div class="ui-g-8">
            <input pInputText [(ngModel)]="selectedStudent.age"  formControlName="age" />
          </div>
        </div>
      </div>
    <button type="button" pButton icon="fa fa-check" (click)="save()" label="Save"></button>
  </p-dialog>
</form>

Answer

Patryk Brejdak picture Patryk Brejdak · Oct 4, 2018

Having ngModel with formGroup is really odd. You should remove ngModel and instead bind on valueChanges on fromGroup and then just iterate through received data and assign values.

 //somewhere where form is build
 this.studentForm.valueChanges.subscribe(data => this.onStudentFormValueChange(data));

 private onStudentFormValueChange(data) {
    this.selectedStudent.age = data.age
    this.selectedStudent.email = data.email
    this.selectedStudent.nameSurname = data.nameSurname

    // or
    for (const key in this.studentForm.controls) {
       const control = this.studentForm.get(key);
       this.selectedStudent[key] = control.value
    }
}