Reputation: 201
I'm a student starting to train on Angular 5. I guess my issue could be the same even on Angular 2.
For a project, i'm currently trying to create a simple search input where the user can write a name of a city, and the field will suggest some names below. Then when the user click on a item of the list, it will be displayed in the input. Actually it should act pretty much like the google search bar.
Here is the plunk. I guess it won't run in plunk because i just put the right files to understand and not my whole app.
Here are my files : input-form.component.html :
<input
type="text"
class="form-control"
id="InputCity"
[(ngModel)]="searchText"
formControlName="city"
(click)="displayCities()">
<ul class="results">
<li>
<a
class="list-group-item"
style="cursor: pointer"
*ngFor="let city of citiesListInput | filter : searchText"
(click)="putIntoField(city)">
{{ city }}
</a>
</li>
</ul>
input-form.component.ts (in short):
export class InputFormComponent implements OnInit {
citiesListInput: string[];
constructor(private citiesSvc: CitiesService) { }
//Get list of cities from a service//
displayCities() {
this.citiesListInput = this.citiesSvc.citiesList;
}
//Should send the city clicked in the list in the input field.//
//For now i just console log it//
putIntoField(city: string) {
console.log(city);
}
}
First issue : The second click event (putintoField) does not seems to work in a list of items. It just does nothing. But if i remove ul and li tags it works. Am i missing something ? If there a way to do it with ul and li tags ?
Second issue : What should i do to put the selected city in the input field ? I'm just missing how to select the value of my input and replace it.
It seems rather simple but i cannot find the right answer on the internets.
Thanks everyone for your answers !
And this is my filter file which is declare in app module :
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
transform(items: any[], searchText: string): any[] {
if(!items) return [];
if(!searchText) return items;
searchText = searchText.toUpperCase();
return items.filter( it => {
return it.toUpperCase().includes(searchText);
});
}
}
Upvotes: 5
Views: 8195
Reputation: 3072
First issue
I don't get any problem in your code. may be you can bind your ul with *ngif
(you can replace your citiesListInput: string[];
to citiesListInput = []
declaration . and check like *ngIf="citiesListInput.length"
. Note: I was replace your array this.citiesListInput = ['dhaka', 'sylet', 'manikganj'];
instead of this.citiesListInput = this.citiesSvc.citiesList;
and its work fine
Second issue
just assign your model
putIntoField(city: string) {
this.searchText = city;
console.log(city);
}
Upvotes: 1