4

I have a form on my site.(person.firstName, lastName, DOB, Gender, Citizenship, etc...). My question is how I can observe whole form changes and get from this observation 2 things:

  • formControl with it's current status
  • current value for handled formControl

    Prefix {{availablePrefix}}

          <div class="col">
            <label for="firstName">First Name<span style="color: red"> *</span> </label>
            <input formControlName="party.firstName" type="text" autocomplete="off" id="firstName"/>
          </div>
    
          <div class="col">
            <label for="middleName">Middle Name</label>
            <input formControlName="party.middleName" type="text" autocomplete="off" id="middleName" maxlength="1" />
          </div>
    
          <div class="col">
            <label for="lastName">Last Name<span style="color: red"> *</span> </label>
            <input formControlName="party.lastName" type="text" autocomplete="off" id="lastName"/>
          </div>
    
          <div class="col">
            <label for="suffix">Suffix</label>
            <select formControlName="party.suffix" id="suffix">
              <option [value]="availableSuffix" *ngFor="let availableSuffix of availableSuffixes">{{availableSuffix}}
              </option>
            </select>
          </div>
        </div>
      </form>
    

thank you for any help

2 Answers2

4

valueChanges observable alwayes will push the new value of the form.

In order to track the state of the form there are several properties for this :

status The validation status of the control. There are four possible validation status values (VALID , INVALID , PENDING, DISABLED).

there is another observable to track the status change statusChanges

other readonly boolean properties to track the state of the form:

(valid , invalid , pending , disabled , enabled , pristine , dirty , touched , untouched)

you can track the old valeu state by this trick

  public form:FormGroup;
  oldValue:any;
  constructor (fb:FormBuilder) { 
     this.form = fb.group({
       name:[],
       lastName:[]
     });

     this.form.valueChanges.subscribe(newValue => { 
        console.log('old value',this.oldValue);
        this.oldValue = newValue;
        console.log('new form value',newValue);
        console.log('state ', this.form.status);
        console.log('pristine ',this.form.pristine);
        console.log('dirty ',this.form.dirty);
        console.log('touched ',this.form.touched);
     });
  }

stackblitz example

AbstractControl

Muhammed Albarmavi
  • 23,240
  • 8
  • 66
  • 91
1

Once your form is created (through the FormBuilder), simply write that :

this.fmdForm.valueChanges.subscribe(formValue => { console.log(formValue); });