Search code examples
angularformsvalidationinputmat-form-field

Angular Form Validator input assigned but return error


In my sing-up component i create a form-group for the validation of the input field.

this.UserForm = new FormGroup({
  name: new FormControl('', Validators.required),
  surname: new FormControl('', Validators.required),
  username: new FormControl('', Validators.compose([
    Validators.required,
    Validators.pattern('^[a-zA-Z0-9._-]+$')
  ])),
  etc...
})

so i have the input with its control

<mat-form-field>
  <mat-label>Name</mat-label>
  <input #name matInput type="text" [value]="userData.name" formControlName="name"
        (change)="onChangeName(name.value)" required>
  <mat-error *ngFor="let validation of account_validation_messages.name">
        <mat-error class="error-message" 
            *ngIf="newUserForm.get('nameUser').hasError(validation.type)
             && (newUserForm.get('nameUser').dirty || newUserForm.get('nameUser').touched)">
                    {{validation.message}}</mat-error>
         </mat-error>
  </mat-form-field>
 <mat-form-field>
 

and it works... but... if i use the same componet for the user update it fills the input with

[value]="userData.name"

and if i "touche" it... it gives me error like it was empty... but it isn't...

How can i fix this error???


Solution

  • You should use newUserForm.get('nameUser').setValue( … ) instead of [value]="…" when using reactive forms.