1

I have a scenario where I have select dropdownlist(classification array). if my selecList has multiple values then ill display as a dropdown. if it has only one element in the array then by default it should be shown in selectList dropdown with that element selected by default. I need to write a condition where if classification element length is less orequal to 1 then show the element selected by default in matselect or display the list. Could you guys advise

<form [formGroup]="myForm">      
      <div formGroupName="Details">        
          <mat-form-field appearance="outline">
            <mat-label class="required">Classification</mat-label>
            <mat-select
              formControlName="classification"              
            >
              <mat-option
                *ngFor="let type of classification"
                [value]="type.definedCode"
              >
                {{ type.definedMessage }}
              </mat-option>
            </mat-select>
          </mat-form-field>

TsFile

classification: any =[
         {
            "definedSetValueCode":"Dry",
            "definedSetValueIntMessage":"Seco"
         }
      ],
Prashanth
  • 45
  • 1
  • 7

1 Answers1

2

I think so you could set has selected value on constructor. I'm assuming you are using reactive forms. (it looks like in your code example).

// if classification looks like this
classification: any = [
  {
   "definedCode":"Dry",
   "definedValue":"Seco"
  }
],

constructor() {
 if (this.classification.lenght === 1) {
    this.myForm.controls.classification.setValue(this.classification[0].definedCode);
 }
}
Luis Reinoso
  • 748
  • 4
  • 13
  • If i dont use reactive from then how can we achieve this – Prashanth Oct 21 '20 at 09:24
  • If you use template forms you should has a variable that has the selected value stored and use NgModel. If you need more details maybe you could check this link: https://stackoverflow.com/questions/47333171/angular-material-mat-select-not-selecting-default – Luis Reinoso Oct 21 '20 at 12:23