Skip to content

formGroup disable()/enable() does not work right after init #22556

Closed

Description

@ctrl-brk

I'm submitting a...


[x] Bug report  

Current behavior

I you create a formGroup using formBuilder.group() and call formGroup.disable() or formGroup.enable() right after initialization then it doesn't work.
If you call it using button or setTimeout() then it works.

Expected behavior

Would be nice to be able to disable/enable form right after creation.

Minimal reproduction of the problem with instructions

View: https://ng-form-disable-after-init.stackblitz.io
Edit: https://stackblitz.com/edit/ng-form-disable-after-init

Environment

Angular version: 5.2.7

Activity

  1. added this to the needsTriage milestone on Mar 2, 2018
  2. Toxicable commented on Mar 3, 2018

    @Toxicable

    Could you explain the steps to reproduce, I don't see anything wrong in your stack blitz

  3. ctrl-brk commented on Mar 3, 2018

    @ctrl-brk
    Author

    Click on "Disable with init" button. It will not disable the form. Or click any other "Disable" and than "Enable with init".

  4. modified the milestones: needsTriage, Backlog on Mar 29, 2018
  5. danguilherme commented on Jun 1, 2018

    @danguilherme

    I am having the same issue, here is a summary of my setup:

    component.ts

    ngOnInit() {
      this.disabledGroup = new FormGroup({});
      this.disabledGroup.disable();
    }

    component.html

    <pre>{{ disabledGroup.disabled }}</pre> <!-- prints: false -->

    Changing this.disabledGroup.disable() to setTimeout(() => this.disabledGroup.disable()); works as expected.

    ng version
         _                      _                 ____ _     ___
        / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
       / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
      / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
     /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                    |___/
    

    Angular CLI: 6.0.3
    Node: 8.11.2
    OS: darwin x64
    Angular: 6.0.2
    ... animations, common, compiler, compiler-cli, core, forms
    ... http, language-service, platform-browser
    ... platform-browser-dynamic, router

    Package Version

    @angular-devkit/architect 0.6.1
    @angular-devkit/build-angular 0.6.1
    @angular-devkit/build-ng-packagr 0.6.3
    @angular-devkit/build-optimizer 0.6.1
    @angular-devkit/core 0.6.1
    @angular-devkit/schematics 0.6.3
    @angular/cli 6.0.3
    @ngtools/json-schema 1.1.0
    @ngtools/webpack 6.0.1
    @schematics/angular 0.6.3
    @schematics/update 0.6.3
    ng-packagr 3.0.0-rc.5
    rxjs 6.1.0
    typescript 2.7.2
    webpack 4.6.0

  6. tjaartvanderWalt commented on Sep 7, 2018

    @tjaartvanderWalt

    I Have the same issue, you can find a minimal working example here

    Environment
    Angular version: 6.1.0

    import { NgModule } from '@angular/core';
    import { ReactiveFormsModule } from '@angular/forms';
    import { BrowserModule } from '@angular/platform-browser';
    import { HttpClientModule } from '@angular/common/http';
    import { PersonService } from './person.service';
    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    
    @Component({
      selector: 'my-app',
      template: `  
            <form [formGroup]="form">    
            <button class="btn btn-primary" (click)="onFetchPerson()">Click Me</button>                
                <div class="form-group">
                    <label>First Name</label>
                    <input type="text" class="form-control" formControlName="firstName" />
                </div>
                <div class="form-group">
                    <label>Surname</label>
                    <input type="text" class="form-control" formControlName="surname" />
                </div>
                <div class="form-group">                
                    Disabled:{{form.disabled}}<br>
                    Status:{{form.status}}
                </div>
            </form>
        `,
    })
    export class App implements OnInit {  
      public form: FormGroup;
    
      constructor(private personService: PersonService) {}
    
      ngOnInit(): void {
        this.form = new FormGroup({     
          firstName: new FormControl(),
          surname: new FormControl(),
        });
      }
    
      public onFetchPerson() {
        this.personService.fetchPerson().subscribe(() => {
          this.form = new FormGroup({        
            firstName: new FormControl('John'),
            surname: new FormControl('Doe'),
          });
          this.form.disable();
          console.log(this.form);
        });
      }
    }
    
    @Injectable({
      providedIn: 'root',
    })
    export class PersonService {
      constructor(private http: HttpClient) {}
    
      public fetchPerson = () => this.http.get('https://randomuser.me/api');
    }
    
    @NgModule({
        imports: [BrowserModule, HttpClientModule, ReactiveFormsModule],
        declarations: [App],
        bootstrap: [App],
        providers: [
            PersonService
        ]
    })
    export class AppModule {}
    

    form-group

  7. Dead96 commented on Sep 11, 2018

    @Dead96

    This simple directive works for me:

    import { Directive, DoCheck } from "@angular/core";
    import { NgControl } from "@angular/forms";
    
    @Directive({
        selector: '[formControlName]'
    })
    export class FixToggleDisableFormControlDirective implements DoCheck {
        private _enabled: boolean;
    
        constructor(private _ngControl: NgControl) { 
            this._enabled = this._ngControl.control.enabled;
        }
    
        ngDoCheck() {
            if (this._ngControl.control.enabled != this._enabled) {
                if (this._ngControl.control.enabled && !this._enabled) {
                    this._ngControl.control.enable();
                }
                else if (!this._ngControl.control.enabled && this._enabled) {
                    this._ngControl.control.disable();
                }
                this._enabled = this._ngControl.control.enabled; 
            }
        }
    }

    Tested on Angular@6.0.5

    UPDATE: Fix calling enable/disable loop

  8. giovannipds commented on Dec 18, 2018

    @giovannipds

    I'm experiencing the same issue. Nothing new about it?

  9. lppedd commented on Jan 21, 2019

    @lppedd

    Same issue on the latest version.
    Damn guys, I was literally going crazy to find what was happening

  10. JohnYoungers commented on Jan 28, 2019

    @JohnYoungers

    I am as well: I have a class that extends FormGroup, where in the constructor it just calls super({...}) to populate the form, then calls disable().

    If I dispatch a new instance of this object to the state, the form in the UI does not render as I'd expect (if the old form was enabled, the fields will still be enabled).

    If I wrap the .disable() line in a setTimeout(), then it works as you'd expect.

  11. 38 remaining items

  12. GonziHere commented on Apr 28, 2021

    @GonziHere

    image
    The warehouse is the root for a whole structure, there might be something down the line that updates value/validity, but nothing, I repeat, nothing, touches the warehouse itself.
    How is that even possible?
    Why is "enabled/disabled" even related to status? (valid beats disabled, so my money is on a validator that "enables" its control and it propagates it up... because that was obviously my intention when I added some validator somewhere... to enable the whole form... ).

    PS: my issue wasn't solvable by timeouts.

  13. added
    P3An issue that is relevant to core functions, but does not impede progress. Important, but not urgent
    and removed
    P4A relatively minor issue that is not relevant to core functions
    on May 27, 2021
  14. self-assigned this
    on Sep 18, 2021
  15. added a commit that references this issue on Sep 22, 2021
    97df03c
  16. added a commit that references this issue on Apr 8, 2022
    d1f2264
  17. angular-automatic-lock-bot commented on Apr 28, 2022

    @angular-automatic-lock-bot

    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.

  18. locked and limited conversation to collaborators on Apr 28, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions