Angular Form Value Changes
Angular reactive forms provide a lot of resources for reacting to users interacting with a form. One of my favorite aspects is the valueChanges property because of how fine-grained you can make it. Take this example of a restaurant order form:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<form [formGroup]="myForm"> | |
<select formControlName="meal"> | |
<option [value]="'dinoburger-special'">Dinoburger Special</option> | |
<option [value]="'caveman-classic'">Caveman Classic</option> | |
</select> | |
<input type="number" formControlName="quantity"> | |
<div formGroupName="extras"> | |
Pickup: | |
<input type="checkbox" formControlName="pickup"> | |
<select multiple formControlName="sides"> | |
<option [value]="'french-fries'">French Friends</option> | |
<option [value]="'extra-cheese'">Extra Cheese</option> | |
<option [value]="'onion-rings'">Onion Rings</option> | |
</select> | |
<input type="text" formControlName="deliveryAddress" *ngIf="myForm.controls['extras'].controls.deliveryAddress"> | |
</div> | |
</form> | |
<pre> | |
{{myForm.getRawValue() | json}} | |
</pre> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
is.myForm = this.formBuilder.group({ | |
meal: ['dinoburger-special'], | |
quantity: [2], | |
extras: this.formBuilder.group({ | |
pickup: [false], | |
sides: [['french-fries', 'extra-cheese']], | |
}), | |
}) | |
// Listen to changes to the entire form | |
this.myForm.valueChanges.subscribe(newValues => { | |
// newValues contains a JSON of the entire form | |
console.log(`newValue: `, newValues) | |
if (newValues.quantity > 10) { | |
alert(`Whoa!! You're getting a ton of burgers! Contact our catering service for big parties!`) | |
// NOTE: This will trigger on EVERY change if the quantity is over 10. Having an alert open every time will be REALLY annoying | |
} | |
}) | |
// We can also have logic based around a specific field | |
// For example: Add a required address field if the order is a delivery | |
this.myForm.controls.extras['controls'].pickup.valueChanges.subscribe(isPickup => { | |
const extrasGroup = <FormGroup>this.myForm.controls.extras | |
if (isPickup) { | |
extrasGroup.addControl('deliveryAddress', this.formBuilder.control([], Validators.required)) | |
} else { | |
extrasGroup.removeControl('deliveryAddress') | |
} | |
}) |