Search code examples
angularangular-forms

Angular form get field value only if form valid


I'm using angular form and have some validations in its fields. Now, I want to get the value of a field whenever it changes, but only if the form is in valid state.

<form [formGroup]="AddEditform" novalidate autocomplete="off">
    <mat-form-field appearance="outline">
        <textarea matInput name="user" formControlName="users" id="user">
        </textarea>
        <mat-error
            *ngIf="!AddEditform.valid && AddEditform.get('users').hasError('maxlength')"
        >
            Exceeded maximum length
        </mat-error>
    </<mat-form-field>
</form>
AddEditform: FormGroup;

constructor(
  private fb: FormBuilder,
) { }

ngOnInit() {

  this.AddEditform = this.fb.group({
    users: [
      '',
      [
        Validators.maxLength(100)
      ],
    ],
  });

  this.AddEditform.get('users').valueChanges.subscribe(data => {
    if (this.AddEditform.valid) {
      console.log(data);
    }      
  });
}

Currently, values are getting printed till the point when first violation is happening. In this case, till 101th character. After that I don't get any values. But why am I getting the first violating value?


Solution

  • Looking at the source code of updateValueAndValidity, my guess is that the valueChanges event of a child form control occurs before its parent control is updated.

    Try to keep a reference of your users' control and check its own valid flag, not the one of the parent.

    ngOnInit() {
        this.UsersControl = this.fb.control('', [Validators.maxLength(100)]);
        this.AddEditform = this.fb.group({
            users: this.UsersControl
        });
    
        this.UsersControl.valueChanges.subscribe(data => {
            if (this.UsersControl.valid) {
                console.log(data);
            }      
        });
    }
    

    Either that, or subscribe to the whole form valueChanges event.

    ngOnInit() {
        this.AddEditform = this.fb.group({
            users: ['', [Validators.maxLength(100)]]
        });
    
        this.AddEditForm.valueChanges.subscribe(data => {
            if (this.AddEditForm.valid) {
                console.log(data['users']);
            }      
        });
    }