Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get boolean option values

I am creating a simple customer management app. One of the functionalities is to filter through the table to list active and inactive customers. My issue is when clicked on the dropdown I can't get the boolean value, that is true/false, but only strings "true"/"false" hence my filter will not work.

Here is my html:

<strong class="ml-2">Active Status</strong>
<select class="ml-1" name="activeStatus" [(ngModel)]="activeStatus">
  <option></option>
  <option value=true>Active</option>
  <option value=false>Not Active</option>
</select>

My table filter pipe:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'tableFilters'
})
export class TableFiltersPipe implements PipeTransform {

  transform(list: any[], filters: Object) {
    const keys = Object.keys(filters).filter(key => filters[key]);
    const filterUser = user => keys.every(key => user[key] === filters[key]);
    return keys.length ? list.filter(filterUser) : list;
  }

}
like image 508
kontenurban Avatar asked Dec 12 '18 14:12

kontenurban


1 Answers

The value property of an HTML option element can only be a string. For example, these select options have string values:

<option value="First">Value 1</option>        // value: "First"
<option [value]="'Second'">Value 2</option>   // value: "Second"
<option [value]="myVar">Value 3</option>      // value: string value of myVar property

In order to pass anything else than a string to ngModel when the option is selected, use the [ngValue] binding. As mentioned in the limited documentation:

@Input() ngValue: any - Tracks the value bound to the option element. Unlike the value binding, ngValue supports binding to objects.

@Input() value: any - Tracks simple string values bound to the option element. For objects, use the ngValue input binding.

In your case, you can use [ngValue] to set boolean values:

<option [ngValue]="true">Active</option>       // value: true (as boolean)
<option [ngValue]="false">Not Active</option>  // value: false (as boolean)
like image 96
ConnorsFan Avatar answered Oct 29 '22 14:10

ConnorsFan