Search code examples
javascriptangularangular7

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


Solution

  • 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;
      }
    }