Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set initial value and validation to ng auto-complete in Angular 7?

In my project I want to do validation and set initial value to an autocomplete. Assume: if user does not select anything in the autocomplete box, we should show an validation error: "please select the country".

Code:

<div style="text-align:center">
  <h1>
    Angular autocomplete
  </h1>
  <img width="100" alt="Angular Logo"
       src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg==">
</div>

<div class="ng-autocomplete">
  <ng-autocomplete
    [data]="countries"
    [searchKeyword]="keyword"
    placeHolder="Enter the Country Name"
    (selected)='selectEvent($event)'
    (inputChanged)='onChangeSearch($event)'
    (inputFocused)='onFocused($event)'
    historyIdentifier="countries"
    [itemTemplate]="itemTemplate"
    [notFoundTemplate]="notFoundTemplate">
  </ng-autocomplete>

  <ng-template #itemTemplate let-item>
    <a [innerHTML]="item.name"></a>
  </ng-template>

  <ng-template #notFoundTemplate let-notFound>
    <div [innerHTML]="notFound"></div>
  </ng-template>
</div>

component.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  keyword = 'name';
  public countries = [
    {
      id: 1,
      name: 'Albania',
    },
    {
      id: 2,
      name: 'Belgium',
    },
    {
      id: 3,
      name: 'Denmark',
    },
    {
      id: 4,
      name: 'Montenegro',
    },
    {
      id: 5,
      name: 'Turkey',
    },
    {
      id: 6,
      name: 'Ukraine',
    },
    {
      id: 7,
      name: 'Macedonia',
    },
    {
      id: 8,
      name: 'Slovenia',
    },
    {
      id: 9,
      name: 'Georgia',
    },
    {
      id: 10,
      name: 'India',
    },
    {
      id: 11,
      name: 'Russia',
    },
    {
      id: 12,
      name: 'Switzerland',
    }
  ];
    selectEvent(item) {
    // do something with selected item
  }

  onChangeSearch(search: string) {
    // fetch remote data from here
    // And reassign the 'data' which is binded to 'data' property.
  }

  onFocused(e) {
    // do something
  }
}

To see full project link: https://stackblitz.com/edit/angular-ng-autocomplete

like image 371
Kumaresan Perumal Avatar asked Jan 26 '23 07:01

Kumaresan Perumal


2 Answers

I had a similar problem. I had to set the value of ng-autocomplete in the subscribe() of a http call. I declare my autocomplete in .ts file: @ViewChild('aziendaAutocomplete') aziendaAutocomplete: any; and then i set the initial value and the value of the input:

this.aziendaAutocomplete.initialValue = this.aziendeList[0]?.FirmName;
this.aziendaAutocomplete.searchInput.nativeElement.value = this.aziendeList[0]?.FirmName;

In my case keyword='FirmName' and it works!

           <div class="ng-autocomplete">
            <ng-autocomplete
              #aziendaAutocomplete
              id="aziendaAutocompleteID"
              [data]="aziendeList"
              placeHolder="Cerca un produttore..."
              [searchKeyword]="keyword"
              (selected)='selectEvent($event)'
              (inputChanged)='onChangeSearch($event)'
              (inputCleared)="onClearSearch()"
              [itemTemplate]="itemTemplate"
              [notFoundTemplate]="notFoundTemplate"
              minQueryLength="3"
              [notFoundText]="notFoundText">
            </ng-autocomplete>
            <input type="number" formControlName="azienda" style="visibility: hidden"/>
            <div *ngIf="submitted && formParamsControl.azienda.errors" [ngClass]="(submitted && formParamsControl.azienda.errors) ? 'invalid-feedback d-block' : '' ">
              <div *ngIf="formParamsControl.azienda.errors.required">Selezionare il produttore</div>
            </div>

            <ng-template #itemTemplate let-item>
              <a [innerHTML]="item.FirmName"></a>
            </ng-template>

            <ng-template #notFoundTemplate let-notFound>
              <div [innerHTML]="notFoundText"></div>
            </ng-template>
          </div>
like image 175
Juri Lucci Avatar answered Jan 29 '23 11:01

Juri Lucci


To set initial value, set [searchKeyword]="initialValue":

initialValue:string = 'India'

<ng-autocomplete
    [data]="countries"
    [searchKeyword]="initialValue"
    [initialValue]="initialValue"
    placeHolder="Enter the Country Name"
    (selected)='selectEvent($event)'
    (inputChanged)='onChangeSearch($event)'
    (inputFocused)='onFocused($event)'
    historyIdentifier="countries"
    [itemTemplate]="itemTemplate"
    [notFoundTemplate]="notFoundTemplate">
</ng-autocomplete>

To check the validity On submit button click, have a span that displays the error message and keep it hidden. If the modelvalue is null, then show it

HTML:

<ng-autocomplete
    [data]="countries"
    [searchKeyword]="initialValue"
    [initialValue]="initialValue"
    placeHolder="Enter the Country Name"
    (selected)='selectEvent($event)'
    (inputChanged)='onChangeSearch($event)'
    (inputFocused)='onFocused($event)'
    historyIdentifier="countries"
    [itemTemplate]="itemTemplate"
    [notFoundTemplate]="notFoundTemplate">
</ng-autocomplete>
    <span class="help-block warning-block" id="invalid-country" *ngIf="showCountryErrorMessage">Please select the country</span>

TS

showCountryErrorMessage:boolean:false

selectEvent(item:any) {
  this.selectedCountry = item
}

onSubmit(){
  if(this.selectedCountry){
     // api call to save data
  } else {
    this.showCountryErrorMessage = true;
  }
}
like image 40
Adrita Sharma Avatar answered Jan 29 '23 12:01

Adrita Sharma