I'm using the repeat template of Dart Polymer to show the items of list. Now, I would like to implement a search filter, where only the items are displayed, which relates to the typed search term. Consider the following code:
my-element.html
<polymer-element name="my-element">
<script type="application/dart" src="my-element.dart"></script>
<template>
<input type="text" value="{{ searchTerm }}">
<ul>
<template repeat="{{ item in items }}">
<template if="{{ matchesSearchFilter(item) }}">
<li>{{ item }}</li>
</template>
</template>
</ul>
</template>
</polymer-element>
my-element.dart
@CustomTag('my-element')
class MyElement extends PolymerElement {
@observable List<String> items = toObservable(["Monday", "Tuesday", "Wednesday"]);
@observable String searchTerm = '';
MyElement.created() : super.created();
matchesSearchFilter(String item) {
if (searchTerm.isEmpty) return true;
return item.toLowerCase().contains(searchTerm.toLowerCase());
}
}
For example, when I type "Mo" in the textbox, I would expect that the list of items updates automatically, such that only "Monday" is shown. However on typing any search term, the list remains the same and the search term is ignored.
So, how to implement such a feature correctly?
An alternative solution would be to make a list
allItems
containing all items and whensearchTerm
changed updateitems
like:In this case you shouldn't need the
toObservable
as it is redundant to observe if items are added or removed. To observe whether theitems
list was replaced the@observable
attribut should be enough.An second alternative is to add a filter :
and
Items will be filtered before being used in the repeat loop. Personally I prefer to use a filter instead of Günter's solution because :
- it's easy
- centralized
- quite understandable to add other filters with pipe operator
- your list is not changed (only filtered)
For example, imagine that you also want to sort your items. Then just add another filter :
Your items will be filtered and then sorted (each time searchTerm, sortField or sortAsc change). Easy ;-)
And the last tips: the previous code will filter your list at each keystroke which is not very user friendly!
Instead you can use that kind of code:
And then in your class