Muirik Muirik -3 years ago 180
TypeScript Question

Clearing md-radio-button selections in Angular 2 App

I have a sorting filter set up on my Angular app, that uses radio buttons via md-radio-group so that users can choose a preferred sorting method on a table display of data. The radio buttons are working as expected. However, I also have a "Restore Defaults" button that I want to use to clear all radio-button selections and return to default sorting. So far I'm having difficulty getting the radio buttons to clear.

This is what my view code looks like:

<filter-option name="Sort"
placeholder="Select Sorting Option"
[usePlaceholder]="!value"
[visible]="sortFilters.enabled">
<filter-label>{{value | capitalize}}</filter-label>
<filter-menu>
<md-radio-group class="mat-radio-label-content">
<md-radio-button value="alphabetical" class="vert-radiobox-list" (click)="onSortClicked(value = 'alphabetical')">
Alphabetical
</md-radio-button>
<md-radio-button value="reverse alphabetical" class="vert-radiobox-list" (click)="onSortClicked(value = 'reverse alphabetical')">
Reverse Alphabetical
</md-radio-button>
<md-radio-button value="numeric ID" class="vert-radiobox-list" (click)="onSortClicked(value = 'numeric ID')">
Numeric ID
</md-radio-button>
</md-radio-group>
<button md-button class="restore-button" (click)="clearSortingFilters()">Restore Defaults</button>
</filter-menu>
</filter-option>


In my component I have this that initializes the filter:

sortFilters =
{
enabled: true,
value: false
};


And this is the function attached to the button to clear the sort filters:

clearSortingFilters()
{
this.sendSort.emit(this.value = '');
}


Now, in the above function,
this.sendSort.emit(this.value = '')
accomplishes clearing the selection that was showing in the filter-label area. But how do I clear the md-radio-group radio button selections as well?

Answer Source

This is how you should modify your code in order to work:

html

<md-radio-group class="mat-radio-label-content" [(ngModel)]="selectedValue">
     <md-radio-button value="alphabetical" class="vert-radiobox-list" (click)="onSortClicked(value = 'alphabetical')">
           Alphabetical
     </md-radio-button>
     <md-radio-button value="reverse alphabetical" class="vert-radiobox-list" (click)="onSortClicked(value = 'reverse alphabetical')">
           Reverse Alphabetical
     </md-radio-button>
     <md-radio-button value="numeric ID" class="vert-radiobox-list" (click)="onSortClicked(value = 'numeric ID')">
           Numeric ID
     </md-radio-button>
</md-radio-group>    
<button md-button class="restore-button" (click)="clearSortingFilters()">Restore Defaults</button>

ts

selectedValue: string;

clearSortingFilters(){
    this.selectedValue = null; // or false or ''
  }

Working plunkr here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download