user9414660
user9414660

Reputation: 106

Angular mat-select not picking up default value

I have a array object of the form

interArray = [{key: "0", value: "1949"},
              {key: "1", value: "2919"},
              {key: "2", value: "4009"},
              {key: "3", value: "6119"},
              {key: "4", value: "7649"},
              {key: "5", value: "9169"}];

My HTML file contains the following:

<mat-select [(ngModel)]="IntransitSelectedValue">
  <mat-option [value]="option.value" *ngFor="let option of interArray" selected>
    {{option.value}}
  </mat-option>
</mat-select>

And my angular component code this is the scenario:

I'm using IntransitSelectedValue in Angular component to read the value and make some manipulations.

I need to pass value: "2919" or any value which will be returned based on some logic & that value Eg: 2919 I need to pass to Angular as a default dropdown to be shown, in this Eg it will be 2919 selected and rest. But nay attempt I was not able to set the default value to preselect

I tried adding selected = "2919" in angular component and in html adding <mat-select [(value)] = selected> but it didn't work.

Upvotes: 0

Views: 354

Answers (1)

if you are using two way binding to read a value, just give it a initial value to you IntransitSelectedValue

import { Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  IntransitSelectedValue: any = '2919';

  interArray = [{key: "0", value: "1949"},
                {key: "1", value: "2919"},
                {key: "2", value: "4009"},
                {key: "3", value: "6119"},
                {key: "4", value: "7649"},
                {key: "5", value: "9169"}];
}

then with the two way binding [(ngModel)]="IntransitSelectedValue" angular knows that the initial value of the select will be equal to IntransitSelectedValue in this case is '2919'

Upvotes: 1

Related Questions