Search code examples
angularangular-formsangular8

Angular select options hide inactive but still show historic value


I am using Angular8 reactive forms. I am creating a form that must be pre-loaded with the details of a selected Item by ID. The details of the Item are displayed in the form by passing in the existing Item values to the FormControl() method. This part is all working properly.

However, the issue is being able to display the default value if the option is being filtered out due to going "inactive" at a later time.

QUESTION: How to populate a default value that no longer exists in the select options array?

EXAMPLE:

The Item form has a select box "Project" that displays a list of projects from the database.

The database query returns "active" projects only. A project is an object with properties _id, ProjectName and Inactive.

// item.project
{"_id":"5d0699380a29581928374651",
"ProjectName":"Server upgrade to version 10",
"Inactive":0}

The _id is being set as the value and the ProjectName set as the display value.

<mat-form-field appearance="outline" floatLabel="always" class="width-50p">
  <mat-label>Project</mat-label>
  <mat-select formControlName="Project">
    <mat-option *ngFor="let project of projects" [value]="project._id">
      {{project.ProjectName}}
    </mat-option>
  </mat-select>
</mat-form-field>

The 'Project' form control is set to the existing project._id as the default.

This works as long as the project isn't being filtered out, due to being set inactive at a later time.

// Initialize form controls
this.itemForm = new FormGroup({
  // other item properties...
  'Project': new FormControl(item.project._id),
});

How can the default value be set to an option that isn't in the select options anymore?

Perhaps I can start by getting the item value and then appending it to the options array, then setting the default in the form control.


Solution

  • You can always add a new option to your mat-select. But you need first make a function like(*)

    find(data:string)
    {
       return this.projects.find(x=>x._id==data)
    }
    

    So you can do some like

    <mat-select formControlName="Project">
        <mat-option *ngFor="let project of projects" [value]="project._id">
          {{project.ProjectName}}
        </mat-option>
    
        <mat-option *ngIf="item?.project?._id && !find(item.project._id)
                    [value]=item.project._id>{{item.ProjectName}}
        </mat-option>
    
    </mat-select>
    

    (*)It's necesary because you can not use in .html some like find(x=>x._id==data)