Background
Im using Reactive Forms that expands over two tabs (first half of the page alone has tabs) and then a long page with Submit button at the bottom. I do the validation on click of the Submit button.
On clicking of Submit button, the page needs to scroll to the error form field when Validation fails.
I'm also able to load the tab based on errors in FormGroups.
Problem
- The scroll happens before the tab loads.
- To solve Point 1, I subscribed to the animationDone event and then scrolled to the point inside of it.
submit(){
//code to select the desired tab
this.selectedTab.animationDone.subscribe(res => {
this.myElement.nativeElement.ownerDocument.getElementsByClassName('ng-invalid mat-form-field')[0].scrollIntoView({ behavior: 'smooth' });
});
}
All works fine until this point !!!
Once the Approve Button is clicked, the subscription subscribes, and the page scrolls to the errors whenever a new Tab is selected. I wanted to unsubscribe to this observable and later subscribe back whenever the Submit button is clicked again.
I tried unsubscribe, but I'm not able to subscribe to it again. This sometimes destroys the subscribe function and throws error
I think I'm missing something and reaching out for help. Thanks in advance !!
More Code as Requested
submit()
{
if(this.bookingForm.valid){
// do some actions ....
}
else {
this.bookingForm.markAllAsTouched();
//subscribing to the event before selecting the tab
this.selectedTab.animationDone.subscribe(res => {
this.myElement.nativeElement.ownerDocument.getElementsByClassName('ng-invalid mat-form-field')[0].scrollIntoView({ behavior: 'smooth' });
});
// code to select the Tab where the error occurs .....
this.selectedTab.selectedIndex = this.errorIndex;
//unsubscribe
this.selectedTab.animationDone.unsubscribe()
} // close of else block
}// close of submit Function
The unsubscribe (or similar function) is required as this should subscribe only when the Submit button is clicked. If it is not unsubscribed (or paused) then the subscribe function is being called everytime the tab is changed and the page keeps scrolling up and down based on errors.
Page View
This is just for demonstration.
EDIT 2 below
Here is the StackBlitz Link. This is just a sample page, My page has much more fields and form Groups compared to this.
Recreating the Issue
Scenario 1
- Fill in the fields - Name , Tab1 , Details1
- Keep tab1 selected and click on Submit.
- This should scroll up and show Tab2. Works as expected! The delay is agreeable.
- Now manually switch to Tab1.
- You can see the page scrolling to the Details 2 field.
- This scroll happens whenever the tab is switched. How do i stop this?
- Im able to achieve this by uncommenting line 38 in app.component.ts file. - The unsubscribe command.
- In this, there is an error when i click on the Submit button more than once.
- When i click for the second time, the subscribe dosen't work.