4
votes

How can a default (i.e. selected) option be set on a Select component when using Material Design for Angular?

<md-select placeholder="Angular2 Material">
  <md-option>One</md-option>
  <md-option selected>Two</md-option>
  <md-option ng-selected="true">Three</md-option>
</md-select>

Searching SO lead me to:

I have tried both ng-selected="true" and selected attribute, neither work.

Plunker: https://plnkr.co/edit/EyC6wpUpgZEihlGclDUU?p=preview

To be clear, I'm not using Material Design for AngularJS Apps. I am using Material Design for Angular.

1
Go to material.angular.io/components/component/select. Read the section titles "Getting and setting the select value". - JB Nizet
@JBNizet This is assuming I have a Component behind my form element. Although my Plunker does indeed have this, can I set a default from the mark-up to avoid having a component for each select element? - Jack
You always have a component. All angular views are views of a component. You don't need a component per select. - JB Nizet
@JBNizet I do have components - but it's a parent component for the entire form. So I should set the default value in the component encompassing the form? - Jack
Yes, that's what you should do. A form is typically used to provide information about an object (a user for example: name, first name, gender, etc.). That object is the model of the form. ngModel allows binding form widgets (like your select) to fields of your model (like your user object). So initialize the model (i.e. the user object), and the form fields will display the information of the user. That's basically what angular is all about. - JB Nizet

1 Answers

5
votes

You should have the variable to store selected value

export class SelectOverviewExample {
  myValue = 'Two';
}

then make sure the md-option has the value attribute. Bind the selected value via ngModel.

<md-select placeholder="Angular2 Material" [(ngModel)]="myValue">
  <md-option>One</md-option>
  <md-option value="Two">Two</md-option>
  <md-option>Three</md-option>
</md-select>