简体   繁体   中英

Set default option in md-select in angular material 2

I am trying to set the default option in md-select of angular-material2 but to no avail.

form2.component.ts:

export class Form2Component implements OnInit {
    frequency = [
                {"title" : "One Time",         "description" : "", "discount" : {"value" : 0,  "type" : "value"} },
                {"title" : "Weekly",           "description" : "", "discount" : {"value" : 20, "type" : "percent"} },
                {"title" : "Every other Week", "description" : "", "discount" : {"value" : 15, "type" : "percent"} },
                {"title" : "Monthly",          "description" : "", "discount" : {"value" : 10, "type" : "percent"} }
            ]
    constructor(){}
    ngOnInit(){}
}

form2.component.html:

<md-select placeholder="Frequency" [formControl]="userForm.controls['frequency']">
    <md-option *ngFor="let frequ of frequency" [value]="frequ" [selected]="frequ.title == 'Weekly'">{{frequ?.title}}</md-option>
</md-select>

Since you are using a reactive form, you can set the default value to the formcontrol. So you can do find the frequency you want from the array and set it as the default value, like:

this.userForm = this.fb.group({
  frequency: this.frequency.find(x => x.title == 'Weekly')
})

And remove selected from your template:

<form [formGroup]="userForm">
  <md-select placeholder = "Frequency" formControlName="frequency" >
    <md-option  *ngFor="let frequ of frequency" [value]="frequ" > {{frequ?.title}} </md-option>
  </md-select>
<form>

Demo

Component HTML

 <md-select placeholder="Favorite food" [(ngModel)]="selectedValue" name="food">
    <md-option *ngFor="let food of foods" [value]="food.value" >
      {{food.viewValue}}
    </md-option>
  </md-select>

  <p> Selected value: {{selectedValue}} </p>

Component.ts

@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;

set the selected value to the value from the array you want it to be default, you are not using two way binding

When you use Objects in md-option value , the object reference of the default value and the correponding option in the options list are not equal .

To fix this, you need to override the default value using the correponding option in the options list before setting the FormGroup .

Here is an example :

my.component.ts

export class MyComponent implements OnInit {

    myobject: Object = {id:'1323', label:'myform', service: {id:'S01', label:'Service 01': desc:''}}
    services: Array<Service> = [
        {id:'S01', label:'Service 01' , desc:'Service desc'},
        {id:'S02', label:'Service 02' , desc:'Service desc'},
        {id:'S03', label:'Service 03' , desc:'Service desc'}];

    myForm : FormGroup;

    constructor(private fb: FormBuilder) {

        // Override the service in  myobject before setting the FormGroup myForm
        this.services.forEach(srv => {
            // Compare service By id
            if (srv.id === myobject.service.id) {
                myobject.service = srv;
            }
        });

        // Set the formGroup with the myobject containing the good reference to the services array.
        this.myForm = this.fb.group(myobject);
    }
}

my.component.html

<md-select class="carrier-select form-control" formControlName="service">
    <md-option class="carrier-option" *ngFor="let service of services" [value]="service">{{service.label}}</md-option>
</md-select>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM