Set default option in mat-select

后端 未结 11 1731
北恋
北恋 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:00

    This issue vexed me for some time. I was using reactive forms and I fixed it using this method. PS. Using Angular 9 and Material 9.

    In the "ngOnInit" lifecycle hook

    1) Get the object you want to set as the default from your array or object literal

    const countryDefault = this.countries.find(c => c.number === '826');
    

    Here I am grabbing the United Kingdom object from my countries array.

    2) Then set the formsbuilder object (the mat-select) with the default value.

    this.addressForm.get('country').setValue(countryDefault.name);
    

    3) Lastly...set the bound value property. In my case I want the name value.

    
       
              {{country.name}}
    
      
    
    

    Works like a charm. I hope it helps

提交回复
热议问题