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;
}
}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With