6

I have multiple auto complete on a page and able to select values and save them. What I need is when I load the page next time, the pre selected values should be displayed by default for the ones already selected and saved.

Following is the code snippet -

<ng-container matColumnDef="course">
      <th mat-header-cell *matHeaderCellDef mat-sort-header> Course Section </th>
      <td mat-cell *matCellDef="let course"> {{course.courseSection}}
      <mat-form-field>
          <input type="text" id="{{course.courseSection}}" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl"
            [matAutocomplete]="auto">
          <mat-autocomplete #auto="matAutocomplete" (optionSelected)="onSelectionChanged(course.courseSection, $event)">
            <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
              {{option}}
            </mat-option>
          </mat-autocomplete>
        </mat-form-field>
      </td>
    </ng-container>

On ngOnInit, I am able to get the values saved in a map and was using the below logic which doesn't work -

checkAssigned(section: string) {
    if (this.assigned.has(section)) {
      return this.assigned.get(section);
    } else {
      return '';
    }
} 

Html -

<mat-option *ngFor="let option of filteredOptions | async" 
[value]="checkAssigned(course.courseSection)===''? option : checkAssigned(course.courseSection)">

But it doesn't work. Any suggestions as how can I achieve it?

enter image description here

a p
  • 1,121
  • 6
  • 26
  • 51

1 Answers1

11

For setting values, it should similar to the format that you're using in the matAutoComplete list.

Suppose you are using like myNameList = [{name:"My Name",id:1},{name:"My name 2",id:2}]

Then for that, you need to set the value

this.myformName.controls['myControl'].setValue({name: "My Name", id:1}); //Working Code

it will set the default value if you are setting like

this.myformName.controls['myControl'].setValue("My Name"); //Not working code

then It will not work.

Please check this for reference https://stackblitz.com/edit/angular-8r153h-kpwhaa?file=app/autocomplete-display-example.ts

VIKAS KOHLI
  • 8,164
  • 4
  • 50
  • 61