How do I set default value on md-select component from angular 2 material design?

后端 未结 3 1457
慢半拍i
慢半拍i 2021-02-18 20:23

I have the following select component that gets populated from a data coming from a rest api. How Can I set default selected value on md-select?

  

        
3条回答
  •  半阙折子戏
    2021-02-18 21:00

    you may try below,

    Component HTML

      
        
          {{food.viewValue}}
        
      
    
      

    Selected value: {{selectedValue}}

    Component script

    @Component({
      selector: 'select-form-example',
      templateUrl: './select-form-example.html',
    })
    export class SelectFormExample {
      foods = [
        {value: 'steak-0', viewValue: 'Steak'},
        {value: 'pizza-1', viewValue: 'Pizza'},
        {value: 'tacos-2', viewValue: 'Tacos'}
      ];
    
    
       // setting this is the key to initial select.
       selectedValue: string = this.foods[0].value;
    }
    

    The key here is setting selectedValue with the initial value.

    Check this StackBlitz.

    Hope this helps!!

提交回复
热议问题