Created
January 24, 2018 04:56
-
-
Save azanebrain/77ba5dac465c8c32f9fc136e3515dd37 to your computer and use it in GitHub Desktop.
Allowing an Angular form to respond to user interactions ~ http://azanebrain.github.io/news/angular-form-value-changes
This file contains 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 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') | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment