Md. Rubel Mia
Md. Rubel Mia

Reputation: 111

Mat-select is not selecting option

I have a form with a mat-select field. I initialize this field with the values coming from backend through an API call. But mat-select is not selecting any values from the options. I tried with all possible answers I have found in Stack Overflow from the previous questions about this issue, but none of those working.

my component's ts file :

levels = [1, 2, 3, 4]; 

ngOnInit() {
      this.myService.getData.subscribe((res) => {
         this.initForm(res);
      })
  } 

 initForm (data) {
    this.myForm = this.fb.group({
      Level: [data ? data : ""]
 });

My component's html file:

<form [formGroup]="myForm">
       <mat-form-field appearance="outline" class="w-100-p">
        <mat-label>Level</mat-label>
        <mat-select formControlName="Level">
       <mat-option value="i" *ngFor="let Level of levels; index as i">{{ Level }}</mat-option>
        </mat-select>
    </mat-form-field>
  </form>

In my levels array it can have only values 1, 2, 3, 4 and response will also contain a value from 1-4. And data is coming correctly I have checked using console log. Basically, in this form I have several fields all of those working correctly except this mat-select field. Other fields are not mat-select field.

Upvotes: 0

Views: 1046

Answers (1)

Lautre
Lautre

Reputation: 165

You can found in this stackblitz 2 workings exemple for your issue.

One of the issue in the code you share is the missing [] on the mat-option value the other I think is the use of the index that start at 0 putting an offset in the data you can have in your form

if it's still not that the issue is not in this part of code

Upvotes: 1

Related Questions