首页 > 解决方案 > 如何在搜索栏 Ionic 4 上设置值?

问题描述

我正在尝试在搜索栏上设置值,但看不到任何示例,只是我想要将列表的值放入搜索栏(执行自动完成搜索栏),我已经完成了以下代码:

HTML

    <ion-searchbar type="text" debounce="500" animated 
    placeholder="Filtrar por país" color="dark"
    (ionChange)="search($event)" clearInput></ion-searchbar>
<ion-list>
    <ion-item *ngFor="let country of countries" (click)="selectCountry($country)">
        {{ country }}
    </ion-item>
</ion-list>

TS

    search(event) {
    console.log(event)
    this.initializeListCountries();
    console.log(this.countries)
    const val = event.target.value;
    if (val && val.trim() != '') {
        this.countries = this.countries.filter((country) => {
            return (country.toLowerCase().indexOf(val.toLowerCase()) > -1);
        })
    }
}

selectCountry(country) {
    let val = country.target.value;

}

谢谢

标签: ionic4searchbar

解决方案


在这里,您需要在类中声明selectedCountry变量并将所选国家/地区分配给该变量,然后您需要像这样在模板中绑定该变量 [value]="selectedCountry"

解决方案

HTML

   <ion-searchbar type="text" debounce="500" animated 
    placeholder="Filtrar por país" color="dark" 
    [value]="selectedCountry"
    (ionChange)="search($event)" clearInput></ion-searchbar>
<ion-list>
    <ion-item *ngFor="let country of countries" (click)="selectCountry(country)">
        {{ country }}
    </ion-item>
</ion-list>

TS

selectedCountry: string;//declare global variable

selectCountry(country) {
    this.selectedCountry = country; //assign value

}

推荐阅读