alim1990
alim1990

Reputation: 4972

Angular 6 cannot get the new value typed inside an input displaying data from ngFor loop data

I am getting data and display it inside an input of a reactive form:

<div *ngFor="let users of getUsersArray; let i = index;">
    <mat-form-field>
        <input matInput color="warn" 
        [value]="users.role_type" 
        formControlName="edit_role_type" placeholder="Role Type">
    </mat-form-field>&nbsp;
</div>

This form control is created inside a reactive form:

'edit_role_type': new FormControl({value:'', disabled: true}, Validators.required),

I have an update button, so if a user wants to update the field with new data:

<button mat-raised-button color="warn" 
    (click)="updateUser(users)" [disabled]="formGroup4.valid">
    <mat-icon>update</mat-icon> Update Data
</button>

If I console the value of users on update button click, I can see the data generated from the *ngFor.

If I changed the value and console it, I only see the old values and the new typed one isn't displayed.

Here is the update button script:

updateUser(users){
    console.log(users)
    let email = this.formGroup4.controls['edit_user_email'].value;
    if(this.formGroup4.get('edit_user_password').hasError('minLength'))
    {
         //Password error
    }
   else if(email!='' && !email.endsWith('@test.org'))
   {
        //return email error
   }
   else
  {
      this.auth.updateUserData(users).subscribe(
        (data)=>{

        },
        (error)=>{
          console.log(error)
        }
      );
    }
  }

Upvotes: 0

Views: 89

Answers (1)

Ludevik
Ludevik

Reputation: 7264

You should not bind [value]="users.role_type" to the input when using reactive forms. Use just formControlName and set the value when creating the FormControl.

In your formGroup you should have a FormArray and create edit_role_type FormControl for each user in your array.

When using reactive forms the model used to prefill the data is not two way bound. Users array will not be changed when input value changes. Instead in your update click handler you should get the data from form: this.formGroup.value and update your users based on the form data.

Or you can drop reactive forms and use model driven forms and use two way binding through [(ngModel)].

Upvotes: 3

Related Questions