Dynamically changing ngModel from button presses – Angular

Issue

I have this code which allows the user to filter by a certain field:

<input type="text" class = "form-control" [(ngModel)]="siteFilter.site_name">
<button type="button"  class="btn btn-default">Address</button>
<button type="button"  class="btn btn-default">Site</button>
<button type="button"  class="btn btn-default">Phone</button>

In the component.ts file:

siteFilter: any = { site_name: '', address:'', phone:'' };

I have 3 buttons that should depending on which one is clicked, change the ngModel.xxx so that it will filter by that respective field.

I tried using an array that held the respective fields, and the button clicks would select the index, but then it was just printing out the string value instead of binding it to that model.

Solution

Similar to the code you posted

Trying to keep to your original structure as much as possible: your buttons could change a filter type, and when clicked – clear other filters.

template

<input type="text" [(ngModel)]="siteFilter[filterType]">

<button type="button"  class="btn btn-default" (click)="changeFilter('address')">Address</button>
<button type="button"  class="btn btn-default" (click)="changeFilter('site_name')">Site</button>
<button type="button"  class="btn btn-default" (click)="changeFilter('phone')">Phone</button>

component

siteFilter;
filterType = 'site_name';

constructor() {
  this.name = `Angular! v${VERSION.full}`
  this.emptySiteFilter();
}

changeFilter(newFilter) {
  this.emptySiteFilter();
  this.filterType = newFilter;
}

emptySiteFilter() {
  this.siteFilter = { site_name: '', address:'', phone:'' };
}

Live plunker demo

Radio button alternative

Although if it was me I’d use a radio button and a single object that the type could change on.

template

<input type="text" [(ngModel)]="filter.value" />

<input type="radio" name="filter" [(ngModel)]="filter.type" value="address"> Address
<input type="radio" name="filter" [(ngModel)]="filter.type" value="site_name"> Site
<input type="radio" name="filter" [(ngModel)]="filter.type" value="phone"> Phone

component

filter = { type: 'site', value: '' }

Alternative plunker that uses radio buttons

Answered By – 0mpurdy

Answer Checked By – Marie Seifert (AngularFixing Admin)

Leave a Reply

Your email address will not be published.