1

I am a beginner in Angular/Angular Material and I have the following problem. I have a template with a selection-list with single selection and a few options:

<mat-selection-list [multiple]="false">
  <mat-list-option>Option 1</mat-list-option>
  <mat-list-option>Option 2</mat-list-option>
  <mat-list-option>Option 3</mat-list-option>
</mat-selection-list>

The normal behavior of that list is that an option is selected when you click on it, and only one option can be selected at a time. However, I would like to add the behavior that the option be "unselected" when you click on it again (as it is presented in the docs). I have fiddled around with MatSelectionList, MatSelectionListChange, and @ViewChild(), trying to emulate the solutions proposed here and here, but to no avail so far. My question is then whether it is doable for these components? (And any solution would be very welcome of course :)) Or is it not worth trying to change the behavior of the componenents, and maybe rather start from scratch, or try bootstrap? Thanks a lot!

0

1 Answer 1

2

As you can see in the Angular Material doc (https://material.angular.io/components/list/api), mat-list-option has the selected property.

So you could play with it. When an option is click (you can add a event on each option to catch the event) then you change the selected property.

Ex :

const options = [{
    label: 'Option 1',
    selected: false
  },
  {
    label: 'Option 2',
    selected: false
  }
]

optionWasClicked(optionClicked) {
  this.options.forEach((option) => option.selected = (optionClicked == option) ? true : false)
}
<mat-selection-list *ngFor="let option of options" [multiple]="false">
  <mat-list-option (click)="optionWasClicked(option)">{{ option.label }}</mat-list-option>
</mat-selection-list>

Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot! that was clear and easy :)

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.