Convert selected option to boolean value

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

I have a select field that should work as a boolean:

 <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 logical one. Is it possible to convert it using a converter or something like this:

Here is 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> 

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); } } 

Trumpet:

 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 is not working properly, because caseSensitive is a binder like a string, not a boolean.

+5
source share
1 answer

By default, select uses use values ​​are strings or are constructed if other types are provided. If you use ngValue , you can use other types, and ngModel save the type.

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

Source: https://habr.com/ru/post/1257835/


All Articles