Jens Jens - 2 months ago 6
TypeScript Question

convert a select option to boolean value

I am learning angular2. Here I have the following Problem:

I have a

select
field which should work as a boolean value:

<select [(ngModel)]="caseSensitive">
<option>false</option>
<option>true</option>
</select>


No if i use it in my Filter it will send as a string not as a boolean. Is it possible to convert it using a converter or something like that:

Here my complete HTML code:

<input [(ngModel)]="nameFilter"/>
<select [(ngModel)]="caseSensitive">
<option>false</option>
<option>true</option>
</select>



<table>
<tr *ngFor="let p of (persons | MyFilter: nameFilter:caseSensitive); let i = index">
<td>{{i + 1 }} </td>
<td>{{
p.givenName+" "+ p.familyName
}}</td>
<td><img src="/img/flags/{{ p.nationality}}.png"></td>

</tr>
</table>


The ts code:

import { Component } from '@angular/core';

import {MyFilter} from './MyFilter';

@Component({
selector: 'pizza-root',
pipes: [MyFilter],
templateUrl: 'app.component.html'
})
export class AppComponent {
public year = new Date().getFullYear();
public persons =[{"givenName":"Paul", "familyName": "Smith", "nationality":"american"},
{"givenName":"Jens", "familyName":"myName1", "nationality":"german"},
{"givenName":"Ernst", "familyName":"myName1", "nationality":"german"},
{"givenName":"Jenny", "familyName":"myName1", "nationality":"german"}];
constructor (){
console.log(this.persons);
}
}


The Pipe:

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

@Pipe({
name: 'MyFilter'
})

export class MyFilter implements PipeTransform{
transform( items: any[], args: string, caseSensitive : boolean ):any {
if (items != null && args != undefined && args != ''){
if (caseSensitive){
console.log("caseSensitive")
return items.filter(item=>item.givenName.indexOf(args)!== -1);
} else {
console.log("caseInSensitive")
return items.filter(item=> item.givenName.toLowerCase().indexOf(args.toLowerCase())!== -1);
}
}
console.log("else")
return items;
}

}


The Problem is, that the pipe not working correctly because
caseSensitive
is the bind as a string not as a boolean value.

Answer

By default the values select uses are strings or they are stringified if other types are provided. If you use ngValue instead, you can use other types and ngModel retains the type.

  <select [(ngModel)]="caseSensitive">
    <option [ngValue]="false">false</option>
     <option [ngValue]="true">true</option>
   </select>