Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reset FormGroupDirective when FormGroup.reset() is called #30987

Closed
DibyodyutiMondal opened this issue Jun 12, 2019 · 12 comments
Closed

Reset FormGroupDirective when FormGroup.reset() is called #30987

DibyodyutiMondal opened this issue Jun 12, 2019 · 12 comments
Labels
area: forms feature: under consideration Feature request for which voting has completed and the request is now under consideration feature Issue that requests a new feature freq2: medium state: needs more investigation
Milestone

Comments

@DibyodyutiMondal
Copy link

DibyodyutiMondal commented Jun 12, 2019

馃殌 feature request

Relevant Package

This feature request is for @angular/forms

Specifically, ReactiveForms

Description

**In Component**
myFormGroup = this.formBuilder.group({
   id: new FormControl(
      null,
      {
           validators: [Validators.required]
      })
   },
   {
       updateOn: 'submit'
   });

**In Template**
<form [formGroup]="myFormGroup">
<mat-form-field appearance="outline">
<mat-label>ID</mat-label>
<input formControlName="id" matInput />
</mat-form-field>
</form>

If a FormGroup is reset by calling myFormGroup.reset() in the typescript file , the related FormGroupDirective is not reset, in the sense, 'mat-errors' are still displayed, as if the controls were not pristine.
Use case: If a field ("id" in this case) is required, on page load, the control is white, even if the validity is 'INVALID'. Once I submit a valid response, I process the response and then I reset the FormGroup, but the required field is now red and asking for input.

PS: There are a lot of related issues. In fact, there are so many, that I could not decide where to put this in. For Ex. #10999 was closed because of lack of use case, but I have given one here. Also in #15741, it is additionally mentioned that this problem particularly comes to the fore in case of asynchronous operations, which in my case, is also coupled with a lot of '*ngIf' templates.

Describe the solution you'd like

FormGroup could emit an event when it is resetting. and then the form group would subscribe to it inside ngOnInit(), and call resetForm() on itself every time the event is emitted.

**Add an event emitter which emits on every reset call**
export class FormGroup {
   <rest of the implementation>

    resetting: EventEmitter<any> = new EventEmitter();
   ^^^might as well make it an @Output(), because that would be great

    reset(value?: any, options?: {
        onlySelf?: boolean;
        emitEvent?: boolean;
    }) {
         this.resetting.emit();
         <rest of the implementation of reset()>;
    }
}

**Merge the directive below with the existing FormGroupDirective**
@Directive({
    selector: 'form[formGroup]'
})
export class ProgrammaticResetDirective {
    constructor(
        private fgd: FormGroupDirective
    ) {
    }

    private subscriptions: Subscription = new Subscription();

    ngOnInit() {        
        this.subscriptions.add(this.fgd.control.resetting.subscribe(() => {
            this.fgd.resetForm();
        }));
    }

    ngOnDestroy() {
        this.subscriptions.unsubscribe();
    }
}

Describe alternatives you've considered

One of the current workarounds is to take a ViewChild of the NgForm, like so

**In Template**
<form [formGroup]="myFormGroup" #myFGD="ngForm">
**In Component**
@ViewChild('myFGD', {static: true}) myFormGroup_directive: NgForm;

and every time I reset the FormGroup, to call resetForm on the ViewChild.
But this is tedious in the sense that the programmer must introduce new variables both in the template and typescript, and remember to call resetForm on the directive along with reset on the FormGroup/

@ngbot ngbot bot added this to the needsTriage milestone Jun 12, 2019
@jasonaden jasonaden added freq2: medium feature Issue that requests a new feature labels Jun 25, 2019
@ngbot ngbot bot modified the milestones: needsTriage, Backlog Jun 25, 2019
@njsent
Copy link

njsent commented Nov 23, 2020

We have the same problem with receiving submit/reset events on child form group controls and dirty state error handling which relies on either the control being dirty or formGroupDirective.submitted = true. We were able to work around receiving the submit event by listening to the parent ngSubmit event:

@Directive({
  selector: '[formGroup]',  // hook into existing [formGroup] directive
})
export class FormGroupParentDirective implements OnInit, OnDestroy {
  constructor(@Self() private formGroupDirective: AngularFormGroupDirective,  // self
    @Optional() @SkipSelf() private parentFormGroupDirective: AngularFormGroupDirective // parent
  ) {}
  ngOnInit() {
    if (this.parentFormGroupDirective) {
      this.parentFormGroupDirective.ngSubmit.pipe(untilDestroyed(this)).subscribe((event) => {
     
   if (!this.formGroupDirective.submitted) 
          this.formGroupDirective.onSubmit(event);   // forward submit event to child form to reflect submitted status
      });
    }
  }
  ngOnDestroy() { }
}

but unfortunately no such event exists for reset, specifically when formGroupDirective.resetForm() is called on the parent. This issue comes to light when working with an 'add + another' scenario where the 2nd and subsequent child form components are always in error state since their formGroupDirective.submitted is always true after the first form submission.

What would solve this issue, aside from auto-propagation of the submitted property on child formGroupDirectives, would be to have a formGroupDirective.ngReset event emitter that we could hook into.

@DibyodyutiMondal
Copy link
Author

Is there an update on this?

@angular-robot
Copy link
Contributor

angular-robot bot commented Jun 4, 2021

Just a heads up that we kicked off a community voting process for your feature request. There are 20 days until the voting process ends.

Find more details about Angular's feature request process in our documentation.

@angular-robot angular-robot bot added the feature: votes required Feature request which is currently still in the voting phase label Jun 4, 2021
@angular-robot
Copy link
Contributor

angular-robot bot commented Jun 24, 2021

Thank you for submitting your feature request! Looks like during the polling process it didn't collect a sufficient number of votes to move to the next stage.

We want to keep Angular rich and ergonomic and at the same time be mindful about its scope and learning journey. If you think your request could live outside Angular's scope, we'd encourage you to collaborate with the community on publishing it as an open source package.

You can find more details about the feature request process in our documentation.

@angular-robot angular-robot bot added the feature: insufficient votes Label to add when the not a sufficient number of votes or comments from unique authors label Jun 24, 2021
@DibyodyutiMondal
Copy link
Author

I, for one, genuinely thought that more people would want this, judging by stackoverflow... So should I close this issue, or is it possible to ask to start voting again in the next development iteration (by which time hopefully it might get more votes?)

@petebacondarwin
Copy link
Member

Getting insufficient votes does not automatically mean it will be closed. But it is a signal that it may not have enough benefit to the community to warrant the effort to implement. In this case, since the votes are quite close to 20, I would expect that it will be included for consideration.

@dylhunn dylhunn added this to Inbox in Feature Requests via automation Jul 14, 2021
@dylhunn dylhunn added state: needs more investigation and removed feature: insufficient votes Label to add when the not a sufficient number of votes or comments from unique authors feature: votes required Feature request which is currently still in the voting phase labels Jul 14, 2021
@dylhunn
Copy link
Contributor

dylhunn commented Jul 14, 2021

I've added it to our triage board for future investigation and consideration.

We'd need to do some additional work to fix this:

  1. Create a clear StackBlitz repro demonstrating the issue's effect
  2. Design the API for the new emitter

@dylhunn dylhunn added the feature: under consideration Feature request for which voting has completed and the request is now under consideration label Jul 14, 2021
@DibyodyutiMondal
Copy link
Author

DibyodyutiMondal commented Jul 15, 2021

I'll see if I can get the stackblitz repo up and and running

Update 1: Stackblitz seems to have some trouble with the new way material theming works (sass api)

Error in src/styles.scss
Error: ENOENT: No such file or directory., '/dev/null'

Update 2: The formgroup as defined inside the component class (ts file) seems to be fixed now. It resets when programmatic reset is triggered. But unable to verify if that state is propagated to angular material.

I think it will be best to provide a github repo instead while Stackblitz does not support angular material. This will allow us to then decide if this is a core angular issue or an issue with angular material

@DibyodyutiMondal
Copy link
Author

DibyodyutiMondal commented Jul 15, 2021

Here is the stackblitz repo, with materia; working partially

https://stackblitz.com/edit/angular-ivy-4phat8

It seems that the issue is now fixed???? - in angular and material version 12.1.2

(Can't confirm because we don't know if the control remains in warn-colour, even though the mat-error disappears)
Even if there is an error, it's extremely likely to be on the material side than core angular.

I think I shall go back and look at some of my actual projects after updating them, and report back.

@dylhunn
Copy link
Contributor

dylhunn commented Jul 15, 2021

@DibyodyutiMondal Thanks for the contribution! Let us know what you find please :)

@AndrewKushnir
Copy link
Contributor

FYI I'm closing this issue for now. Please reopen or create a new one if the problem still exists. Thank you.

Feature Requests automation moved this from Inbox to Closed Jul 16, 2021
@angular-automatic-lock-bot
Copy link

This issue has been automatically locked due to inactivity.
Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

This action has been performed automatically by a bot.

@angular-automatic-lock-bot angular-automatic-lock-bot bot locked and limited conversation to collaborators Aug 16, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
area: forms feature: under consideration Feature request for which voting has completed and the request is now under consideration feature Issue that requests a new feature freq2: medium state: needs more investigation
Projects
No open projects
Development

No branches or pull requests

6 participants