Set default option in mat-select

后端 未结 11 1675
北恋
北恋 2020-11-30 08:31

I have a simple select option form field in my Angular material project:

component.html

  
    

        
相关标签:
11条回答
  • 2020-11-30 09:03

    HTML

    <mat-form-field>
    <mat-select [(ngModel)]="modeSelect" placeholder="Mode">
      <mat-option *ngFor="let obj of Array"  [value]="obj.value">{{obj.value}}</mat-option>
    </mat-select>
    

    Now set your default value to

    modeSelect

    , where you are getting the values in Array variable.

    0 讨论(0)
  • 2020-11-30 09:06

    It took me several hours to figure out this until the similarity of the datatypes between the array and that of the default value worked for me...

    0 讨论(0)
  • 2020-11-30 09:08

    Working StackBlitz

    No need to use ngModel or Forms

    In your html:

     <mat-form-field>
      <mat-select [(value)]="selected" placeholder="Mode">
        <mat-option value="domain">Domain</mat-option>
        <mat-option value="exact">Exact</mat-option>
      </mat-select>
    </mat-form-field>
    

    and in your component just set your public property selected to the default:

    selected = 'domain';

    0 讨论(0)
  • 2020-11-30 09:10
    I was able to set the default value or whatever value using the following:
    
    Template:
              <mat-form-field>
                  <mat-label>Holiday Destination</mat-label>
                  <mat-select [(ngModel)]="selectedCity" formControlName="cityHoliday">
                    <mat-option [value]="nyc">New York</mat-option>
                    <mat-option [value]="london">London</mat-option>
                    <mat-option [value]="india">Delhi</mat-option>
                    <mat-option [value]="Oslo">Oslo</mat-option>
                  </mat-select>
              </mat-form-field>
    
    Component:
    
    export class WhateverComponent implements OnInit{
    
    selectedCity: string;    
    
    }
    
    ngOnInit() {
        this.selectedCity = 'london';
    } 
    
    }
    
    0 讨论(0)
  • 2020-11-30 09:13

    I would like to add to Narm's answer here and have added the same as a comment under her answer.

    Basically the datatype of the value assigned to [(value)] should match the datatype of the [value] attribute used for the mat-options. Especially if some one populates the options using an *ngFor as below

    <mat-form-field fxHide.gt-sm='true'>
            <mat-select [(value)]="heroes[0].id">
              <mat-option *ngFor="let hero of heroes" [value]="hero.id">{{ hero.name }}</mat-option>
            </mat-select>
    </mat-form-field>
    

    Notice that, if you change the [(value)]="heroes[0].id" to [(value)]="heroes[0].name" it won't work as the data types don't match.

    These are my findings, please feel free to correct me if needed.

    0 讨论(0)
提交回复
热议问题