12

in angular material 2, How can I set default selected button in toggle group.

It does toggle once I tap one, but both selected by default somehow. I tried as follows, but doesn't work.

  <md-button-toggle-group #group="mdButtonToggleGroup">
    <md-button-toggle (click)="firstTapped()" selected>
      <span>one</span>
    </md-button-toggle>
    <md-button-toggle (click)="secondTapped()">
      <span>second</span>
    </md-button-toggle>
  </md-button-toggle-group>
0

3 Answers 3

23

You need to assign each button a value and then you can give the group an initial value (matching one of the buttons);

<md-button-toggle-group #group="mdButtonToggleGroup" value="button1">
    <md-button-toggle value="button1">
      <span>one</span>
    </md-button-toggle>
    <md-button-toggle value="button2">
      <span>second</span>
    </md-button-toggle>
  </md-button-toggle-group>
Sign up to request clarification or add additional context in comments.

Comments

8

I'm just beginner in material but this should work. You can use ngModel with variable that can have two values "one", "two". Than you can observe changes using "yourFunction".

<md-button-toggle-group (ngModelChange)="yourFunction($event)" [ngModel]="selected">
 <md-button-toggle value="one">
  <span>one</span>
 </md-button-toggle>
 <md-button-toggle value="two">
  <span>second</span>
 </md-button-toggle>
</md-button-toggle-group>

Comments

0

Use checked instead of selected, like:

<md-button-toggle (click)="firstTapped()" checked>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.