简体   繁体   中英

How to reset input value with PrimeNG

I have encountered one problem. I am trying to reset the input value, when I unclick it but it does not work with PrimeNG. I have tried @ViewChild decorator but it did not work. Could someone tell me how can I reset written value when I unclick my input field?

<p-autoComplete [(ngModel)]="brand" [suggestions]="filteredBrands" (completeMethod)="filterBrands($event)" [size]="30"
[minLength]="1" placeholder="Hint: type 'v' or 'f'" [dropdown]="true">
<ng-template let-brand pTemplate="item">
    <div class="ui-helper-clearfix">
        <div style="font-size:18px;margin:10px 10px 0 0">{{brand}}</div>
    </div>
</ng-template>
import { Component } from '@angular/core';
import {MenuItem} from 'primeng/api';
import {SelectItem} from 'primeng/api';
import {SelectItemGroup} from 'primeng/api';
import { CountryService } from './countryservice';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  providers: [CountryService]
})
export class AppComponent { 

brands: string[] = ['Audi','BMW','Fiat','Ford','Honda','Jaguar','Mercedes','Renault','Volvo','VW'];

filteredBrands: any[];

brand: string;

constructor(private countryService: CountryService) { }
    
filterBrands(event) {
    this.filteredBrands = [];
    for(let i = 0; i < this.brands.length; i++) {
        let brand = this.brands[i];
        if (brand.toLowerCase().indexOf(event.query.toLowerCase()) == 0) {
            this.filteredBrands.push(brand);
        }
    }
}
}

Thank you.

enter link description here

So you can set brand to empty string. (onBlur) set your brand = '' Like Following:

On you html file p-autocomplete add this (onBlur)="check()" . You could directly set the brand to empty string but it will happen always when you click outside. so a check function that will see in your array if it finds the string inside it, if its true it will not clear else it will. Here is the ts code check() function:

check() {
  if(this.brands.indexOf(this.brand) != -1) {
    console.log('inside if, found',this.brand);
  } else {
    console.log('not found');
    this.brand = '';
  }
}

This is working perfectly, just one caveat is that you will feel slight snapping after selection because while selecting value it is onBlur as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM