Reputation: 1058
I'm working on an app where we have a page with an order form. The user can either enter a new order, or select from a list of existing orders which will then populate the order form based on that selection. I'm trying to implement validation based on whether or not the user has begun to input data for a 'new' order and then makes a selection from the existing orders. If they have begun to enter data, I want to throw a confirmation dialog alerting them that they will overwrite what they have already entered. I'm trying to figure out how to capture the radio button selection before it's actually changed, to see if they're coming from 'new' to 'existing', and then perform some validation
The template code:
<mat-radio-group formControlName="orderAction" (change)="onOrderActionBlur($event)">
<mat-radio-button value="new" >New Order</mat-radio-button>
<mat-radio-button value="existing">Existing Order</mat-radio-button>
</mat-radio-group>
And in the controller:
onOrderActionBlur($event): any {
this.orderAction= this.form.get('orderAction').value;
if (this.orderAction=== 'new') {
// make sure the fields haven't been changed
}
}
I thought I could use the blur event but when I select off of new, the value is existing. There's probably a better approach, totally open to suggestions as I'm new to Angular. Thanks in advance.
Upvotes: 1
Views: 441
Reputation: 6283
Form controls have many different attributes which you can use to understand the current state they are in.
dirty
will be a boolean, representing whether the form control value has been changed, touched
might also be useful for you, allowing you to know if the control has been touched by the user.
onOrderActionBlur($event): any
{
this.orderAction= this.form.get('orderAction');
if (this.orderAction.dirty)
{
// control value has been modified
}
else
{
// control value has not been modified
}
}
You may not want your application to display errors before the user has a chance to edit the form. The checks for dirty and touched prevent errors from showing until the user does one of two things: changes the value, turning the control dirty; or blurs the form control element, setting the control to touched.
Documentation surrounding controls.
Upvotes: 2