Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular form control not updating the UI just the value

I have a form like this:

this.filterFormGroup= this.formBuilder.group({
      gmt_scope: [''],
      priority: [''],
      region: [''],
      category: [''],
      status: [''],
      original_deadline: [''],
      responsibles: [''],
      pms: [''],
      updated_at: ['']
    });

The form is populated through API:

<form [formGroup]="filterFormGroup" >
          <div fxLayout="row" fxLayoutWrap="wrap" fxLayout="center center"  class="row">
            <div fxFlex.gt-sm="20" fxFlex="100" class="p-10" fxLayoutAlign="center center">
              <!-- <mat-slide-toggle color="primary" stepper="0" formControlName="gmt_scope">GMT SCOPE</mat-slide-toggle> -->
              <mat-form-field>
                <mat-select  placeholder="GMT Scope" stepper="0" formControlName="gmt_scope" >
                  <mat-option *ngFor="let gmt_scope of gmt_scopes" [value]="gmt_scope.value" >
                    {{ gmt_scope.viewValue }}
                  </mat-option>
                </mat-select>
              </mat-form-field>
            </div>
            <div fxFlex.gt-sm="20" fxFlex="100" class="p-10" fxLayoutAlign="start center">
              <mat-form-field>
                <mat-select placeholder="Priority" stepper="0" formControlName="priority">
                  <mat-option *ngFor="let priority of projectAttributes.priorities" [value]="priority.id" >
                    {{ priority.description }}
                  </mat-option>
                </mat-select>
              </mat-form-field>
            </div>

Once is ready I read some queryParams and set some field of the form like these:

setFiltersFromParams(params){
    if ('pms' in params){
      this.filterFormGroup.controls.pms.setValue(params.pms.split(","));
      console.log("Setting the following pms:",params.pms.split(",") )
    }
    if ('region' in params){
      this.filterFormGroup.controls['region'].setValue(params.region,{emitEvent: true});
      console.log("Setting the following region:",params.region )
    }

  }

If I check the control values they are updated correctly but from the UI I can't see the option selected they are unselected.

like image 465
Kerby82 Avatar asked Sep 21 '18 16:09

Kerby82


1 Answers

As you said your GUI is not updated the values but the control values in variable is updated This problem is related to change Detection.

do one thing inject the ChangeDetectorRef service at component level i.e.

define private ChangeDetectorRef cdin the constructor of component.

and where you do the updation of controls programatically in custom event function call this function like this cd.detectChanges().

follow this link it will helpful.

like image 164
Sunny Goel Avatar answered Nov 14 '22 21:11

Sunny Goel