Currently, I am delving into the world of Angular 2 and facing a particular issue:
In my code, there is a select
element designed to function as a boolean value:
<select [(ngModel)]="caseSensitive">
<option>false</option>
<option>true</option>
</select>
The problem arises when this value is sent as a string instead of a boolean in my Filter. Is there any way to convert it using a converter or similar method?
Below is my complete HTML code snippet:
<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>
Also, here is the TypeScript code for reference:
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);
}
}
This Pipe contains the filtering logic:
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 main issue lies in the fact that the pipe does not work correctly due to the binding of caseSensitive
as a string rather than a boolean.