GithubHelp home page GithubHelp logo

gmerabishvili / angular-ng-autocomplete Goto Github PK

View Code? Open in Web Editor NEW
156.0 6.0 88.0 4.79 MB

NPM package for Angular: https://www.npmjs.com/package/angular-ng-autocomplete

License: MIT License

JavaScript 4.75% TypeScript 66.99% HTML 20.76% SCSS 7.49%
angular autocomplete angular-ng-autocomplete angular-autocomplete

angular-ng-autocomplete's Introduction

Angular Autocomplete

Table of contents

Features

  • Flexible autocomplete with client/server filtering.
  • Variable properties and event bindings.
  • Selection history.
  • Custom item and 'not found' templates.
  • Infinite scroll.
  • Compatible with Angular forms API (Both Reactive and Template-driven forms).
  • Keyboard navigation.
  • Accessibility.

Getting started

Step 1: Install angular-ng-autocomplete:

NPM

npm i angular-ng-autocomplete

Step 2: Import the AutocompleteLibModule:

import {AutocompleteLibModule} from 'angular-ng-autocomplete';

@NgModule({
  declarations: [AppComponent],
  imports: [AutocompleteLibModule],
  bootstrap: [AppComponent]
})
export class AppModule {}

Usage sample

<div class="ng-autocomplete">
<ng-autocomplete 
  [data]="data"
  [searchKeyword]="keyword"
  placeholder="Select country"
  (selected)='selectEvent($event)'
  (inputChanged)='onChangeSearch($event)'
  (inputFocused)='onFocused($event)'
  [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>
class TestComponent {
  keyword = 'name';
  data = [
    {
      id: 1,
      name: 'Georgia'
    },
     {
       id: 2,
       name: 'Usa'
     },
     {
       id: 3,
       name: 'England'
     }
  ];


  selectEvent(item) {
    // do something with selected item
  }

  onChangeSearch(val: string) {
    // fetch remote data from here
    // And reassign the 'data' which is binded to 'data' property.
  }
  
  onFocused(e){
    // do something when input is focused
  }
}

API

Inputs

Input Type Default Required Description
[data] Array<any> null yes Items array. It can be array of strings or array of objects.
searchKeyword string - yes Variable name to filter data with.
customFilter (items: any[], query: string) => any[] undefined no Custom filter function. You can use it to provide your own filtering function, as e.g. fuzzy-matching filtering, or to disable filtering at all (just pass (items) => items as a filter). Do not change the items argument given, return filtered list instead.
selectedValueRender (value: any) => string undefined no Custom renderer function to render selected value inside input field.
placeholder string - no HTML <input> placeholder text.
heading string - no Heading text of items list. If it is null then heading is hidden.
initialValue any _ no Initial/default selected value.
focusFirst boolean false no Automatically focus the first matched item on the list.
historyIdentifier string _ no History identifier of history list. When valid history identifier is given, then component stores selected item to local storage of user's browser. If it is null then history is hidden. History list is visible if at least one history item is stored. History identifier must be unique.
historyHeading string Recently selected no Heading text of history list. If it is null then history heading is hidden.
historyListMaxNumber number 15 no Maximum number of items in the history list.
notFoundText string Not found no Set custom text when filter returns empty result.
isLoading boolean false no Set the loading state when data is being loaded, (e.g. async items loading) and show loading spinner.
minQueryLength number 1 no The minimum number of characters the user must type before a search is performed.
debounceTime number _ no Delay time while typing.
disabled boolean false no HTML <input> disable/enable.

Outputs

Output Description
(selected) Event is emitted when an item from the list is selected.
(inputChanged) Event is emitted when an input is changed.
(inputFocused) Event is emitted when an input is focused.
(inputCleared) Event is emitted when an input is cleared.
(opened) Event is emitted when the autocomplete panel is opened.
(closed) Event is emitted when the autocomplete panel is closed.
(scrolledToEnd) Event is emitted when scrolled to the end of items. Can be used for loading more items in chunks.

Methods (controls)

Name Description
open Opens the autocomplete panel
close Closes the autocomplete panel
focus Focuses the autocomplete input element
clear Clears the autocomplete input element

To access the control methods of the component you should use @ViewChild decorator. See the example below:

<ng-autocomplete #auto></ng-autocomplete>
class TestComponent {
  @ViewChild('auto') auto;

  openPanel(e): void {
    e.stopPropagation();
    this.auto.open();
  }
  
  closePanel(e): void {
    e.stopPropagation();
    this.auto.close();
    }
    
  focus(e): void {
    e.stopPropagation();
    this.auto.focus();
  }  
}

Styles

If you are not happy with default styles you can easily override them:

<div class="ng-autocomplete">
<ng-autocomplete></ng-autocomplete>
</div>
.ng-autocomplete {
    width: 400px;
}

Support Angular autocomplete!

If you do love angular-ng-autocomplete I would appreciate a donation :)

Author

License

MIT

angular-ng-autocomplete's People

Contributors

abdurrahmanar avatar borsch avatar cxspxr avatar dependabot[bot] avatar gmerabishvili avatar julitroalves avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

angular-ng-autocomplete's Issues

Panel close automatically clean input

This lib is very great, congratulations !!

I have a question, I am trying to close the panel automatically when the input is clean, reading the documentation it triggers the event (inputCleared).

Even though I'm using #auto and activating this.auto.close() it does not close!

Could you help me with that?

https://stackblitz.com/edit/angular-mapkmv

Thank you ☺

[searcKeyword] functionality

Hi, is it possible to ignore search keyword functionality, because i do search logic in backend, and i search by multiple criteria, so if user enters short name, i cant display it because its not the same as full name

Not found

Instantiated the control and supplied a valid JSON object :

{taxonomy_id: "1", taxonomy: "Taxonomy 1"},{ {taxonomy_id: "2", taxonomy: "Taxonomy 2"}

From the HTML template :

<ng-autocomplete
id="taxonomy" #taxonomy
[data]="data"
[searchKeyword]="keyword"
(selected)='selectEvent($event)'
(inputChanged)='onChangeSearch($event)'
(inputFocused)='onFocused($event)'
[itemTemplate]="itemTemplate"
[notFoundTemplate]="notFoundTemplate">

Using this for onchange

onChangeSearch(val: string) {
this.taxonomy.getAll().subscribe((result:Taxonomy[])=>{
this.auto.data = result;
});
}

The event fires ok, and without errors.

Just always fires the unfound template. Why?

Package needs a license

I was hoping to make use of this package, but without a license, it would be illegal for me to use in a for profit project.

If you want to allow companies to make use of the tool, I'd suggest MIT or BSD style license.
It removes any ambiguity.

If you want to force it to be open sourced in perpetuity, you can use a GPL style license.

changing [(ngModel)] programmatically

Hi,

Great tool!! thank you.

I have a problem when trying to change [(ngModel)] from the ts file or when the ng-autocomplete is in ngIf Div and the condition changes from true to false and to true again.

What happens is that I have an item selected and shows up great, but when I change the ngIf condition to false and then to true the text changes to "[object Object]".

The same thing happens when I change the value of the varible inside the ngModel to another item from the list.

Example:
html file:

<ng-autocomplete [data]="mothers" [searchKeyword]="keyword"
                 [itemTemplate]="itemTemplate" [(ngModel)]="selectedMother">
</ng-autocomplete>
<ng-template #itemTemplate let-item>
    <a [innerHTML]="item.FirstName"></a>
</ng-template>

TS file:

this.selectedMother = this.mothers[1];
// if the selectedMother is already mothers[1] then nothing happens,
// but if the selectedMother is mother[0] for example then the text changes to "[object Object]".

I need to be able to select an item from ts file. Is that possible?
Thanks.

Can we search after when user enter 3 to 4 characters ?

Hi ,
I want to add autocomplete only when when user enter first 3 to 4 characters and after that result should show . Can we do in that way ? I can see in documentation two methods are there 1) onChangeSearch 2)onFocused but not sure how i can achive.

Issue with multiple autocomplete component in the same page.

Thank you for providing the autocomplete component. I am using this component for multiple fields within a page. The issue I encounter is multiple dropdowns could be opened at the same time as demonstrated within below screenshot. I was wondering if you could have a look at this issue and help me to figure out a way to avoid this behavior.

image

Step to reproduce:
1-Select an element from the first field
2-click on the second field
3-click on the close button(x) on the first field
4-click on the close button (x) on the available options.

Filter problem

I have a problem that I can not solve, I am performing a search in my database but the keyword is treated, I realized that when the return comes, it is displayed that no records were found, because what was searched for example RESSONANCIA is different from the RESSONÂNCIA result (No ^), I would like it not to filter the result by the keyword this is possible, ie I just want to show me the result of the api.

Trigger open on focus

I have method which works on input focus in autocomplete and I defined autocomplete as ViewChild.
But when I try to open autocomplete (this.autocomplete.open()) on focus it wont open. I just want to open autocomplete on first focus without typing anything.

Stop Submitting form on selected event.

I am using autocomplete in form but as soon as i hit enter for select value it submit form.
I gave tried this code but not working

  closePanel(e): void {
    e.stopPropagation();
    this.auto.close();
  }

Expose Control State (pristine, untouched, etc)

This may be user ignorance, but it would be nice if you could access the state of the control for use in template driven forms. I would like to be able to determine if the control is pristine, touched, etc similar to native angular template reference variables.

This could be achieved through the component markup or when adding the component as a @ViewChild in a typescript file.

I'm simply looking for a way to do some simple validation against this control such as making it required.

How Can I add Data Dynamically ?

this.countryList.push({
  id: 13,
  name: 'Newly Added',
});

 view.html
  <ng-autocomplete
   [data]="countryList"
   </ng-autocomplete>

the above contryList is the array type and the data is fetch only which is in static data added in the ts file.

While i trying to add new country to country list it is added but not updated in the view of autocomplete, how can i make this visible in the view ?

ng-autocomplete [disabled]=true not working

                <div class="ng-autocomplete">
                  <ng-autocomplete #make [placeHolder]="'Vehicle Make'" [data]="makeList"
                    [(ngModel)]="selectedMakelist.VehicleMake" [ngModelOptions]="{ standalone: true }"
                    [searchKeyword]="keyword" (selected)="selectEvent($event)" [itemTemplate]="itemTemplate"
                    [notFoundTemplate]="notFoundTemplate" [disabled]=true></ng-autocomplete>
                  <ng-template #itemTemplate let-item>
                    <a [innerHTML]="item.VehicleMake | safeHtml"></a>
                  </ng-template>
                  <ng-template #notFoundTemplate let-notFound>
                    <div [innerHTML]="notFound | safeHtml"></div>
                  </ng-template>
                </div>

Styling not working

Hi, i've been trying to change border style using class="ng-autocomplete" but i was unable to do it, is there a way to do it?

IE Issue - Item Click is not firing

Steps to replicate - Open in IE 11 browser.

  1. Focused the input text
  2. When drop down show click on any item.

Temporary fixed - on my fork copy - I changed it to mouse down.

Feature Request: Custom Classes for icons

Would like the ability to set the classes on the spinner and x icons, so we're not forced to use the ones included and can utilize font icons already within our UI.

IE/Edge Close(x) icon duplicate

Within IE and Edge browser there is a case that close icon (x) will be doubled per blow screenshot.

image

Step to reproduce:
1- select and item form the component.
2- click on the component again.

Thanks in advance.

Could we get the ability to change the input type to prevent browser autocomplete?

Would it be possible to get an update to also allow changing the input type of the search field.

Personally I would like to set the type to search to prevent browsers from popping up their own autocomplete which destroys the user experience.

I've seen other issues like #43 that would like a number type field.

I don't mind making a PR if I could find out which project to fork and update. Maybe you could tell me that and I'll make the PR so everyone can enjoy this feature?

Thanks.

How to set default value for the input.?

Hi,

How can I set the default value for the input. Even I tried using the initialValue parameter but nothing works. Kindly help me regarding this issue as soon as possible.

Thanks & regards,
Vignesh Mohanraj

Got warning while ng serve - export 'defineInjectable' was not found in '@angular/core'

WARNING in ./node_modules/angular-ng-autocomplete/fesm5/angular-ng-autocomplete.js
22:64-80 "export 'defineInjectable' was not found in '@angular/core'
at HarmonyImportSpecifierDependency._getErrors (/home/venkat/Desktop/Projects/Amn-angualr/node_modules/webpack/lib/dependencies/HarmonyImportSpecifierDependency.js:65:15)
at HarmonyImportSpecifierDependency.getWarnings (/home/venkat/Desktop/Projects/Amn-angualr/node_modules/webpack/lib/dependencies/HarmonyImportSpecifierDependency.js:39:15)
at Compilation.reportDependencyErrorsAndWarnings (/home/venkat/Desktop/Projects/Amn-angualr/node_modules/webpack/lib/Compilation.js:694:24)
at Compilation.finish (/home/venkat/Desktop/Projects/Amn-angualr/node_modules/webpack/lib/Compilation.js:552:9)
at applyPluginsParallel.err (/home/venkat/Desktop/Projects/Amn-angualr/node_modules/webpack/lib/Compiler.js:512:17)
at /home/venkat/Desktop/Projects/Amn-angualr/node_modules/tapable/lib/Tapable.js:289:11
at _addModuleChain (/home/venkat/Desktop/Projects/Amn-angualr/node_modules/webpack/lib/Compilation.js:498:11)
at processModuleDependencies.err (/home/venkat/Desktop/Projects/Amn-angualr/node_modules/webpack/lib/Compilation.js:468:14)
at process._tickCallback (internal/process/next_tick.js:61:11)

And in the browser console is I got this error "TypeError: Object(...) is not a function" and app stops working

Trouble when build

I am using Angular CLI 7.1.4. When i build, get this error:

ERROR in ./node_modules/angular-ng-autocomplete/autocomplete-lib.ngfactory.js
Module not found: Error: Can't resolve 'autocomplete-lib'

How can i fix it?

Thanks!

keyWord Not updating when changed

Hi! I love your tool and its works great! One minor issue I found is when passing a dataset and trying to point out which variable in the objects to use by updating the keyword, it does not update on focus, only when the user starts typing. Its possible I'm using something wrong, but I thought id report it either way. I will attach pictures to try to better explain what I'm seeing. Thanks!

I changed the key word and the variables in the object to be 'cname' instead of just name and this is what happens.

2019-03-11_09h34_01
2019-03-11_09h34_13

Library fails to work if class is used instead of object for data input

Hello. Sorry if I write this in bad structure, but i haven't done it before. So, there's a bug in autocomplete with classes. If i provide interface like this:

export interface Test {
  id: number
  name: string
}

And after that I initialize interface and give it as data to autocomplete:

testData: Test[] = [
{
  id: 2,
  name: 'hello'
},
{
  id: 4,
  name: 'test'
}]

Everything works as expected. But, If i were to replace interface with class

export class Test {
  id: number;
  name: string;

  constructor(id: number, name: string){
    this.id = id;
    this.name = name;
  }
}

And after that and give it as data to autocomplete:

testData: Test[] = [];
testData.push(new Test(2, 'hello'));
testData.push(new Test(4, 'test'));

Autocomplete simply won't work. Nothing will be shown.
I did go through code and found out the reason it is not working on line

} else if (typeof item === 'object' && item.constructor === Object) {

When i give concrete class the item.constructor contains:

ƒ Test(id, name) {
        this.id = id;
        this.name = name;
    }

instead of expected

ƒ Object() { [native code] }

My solution is to change && item.constructor === Object into && item instanceof Object

Allow disabling the input

Hi!, i really like this control, its simple and works like a charm.

Is there a chance you can add to it the posibility to disable/enable it?

isLoading isn't working properly

If isLoading is set (doesn't matter true of false), the loading spinner keeps on showing. However, we can directly set isLoading = "" (i.e empty string) to act as if it was set to false.

How set custom css for autocomplete input?

I am trying to set css for autocomplete height and auto suggestion list z-index but they are not working. I am like bellow,

.autocomplete-container .input-container input {
  font-size: 14px;
  padding: 0 6px;
  height: 25px;
}
.autocomplete-container .suggestions-container {
  z-index: 9999;
}

reset value of [(ngModel)] is not updating in html view (angular 7)

I am using angular 7 and want to reset [(ngModel)] value but its not update the view by null or '' .

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

if once we assign some value to selected.Country then if we assign/reset to null or empty it not reflect to view.

cannot serve app with Ivy

It seems that this piece of code cannot be used with Ivy

// custom templates @ContentChild(TemplateRef) @Input() itemTemplate: TemplateRef<any>; @Input() notFoundTemplate: TemplateRef<any>;

As I'm getting the following error message

Cannot combine @input decorators with query decorators

Need help on this part.

Thanks

Problem with Style, does not get applied

Hello there @gmerabishvili , I hope that you're doing great,

My issue is regarding the styling of the Ng-Autocomplete, I don't succeed to apply the style that I want to apply on the component, even that I can get the result using the browser, when using the "ng-autocomplete" class, nothing happen.

PS : I made some research in old posts before asking, I believe it's something close to what you've talked about here #40 (comment) ; but trying that out didn't work for me too, actually, the /deep/ isn't accepted by .css nor .scss style-sheets.

I would be very thankful if you could point me what I might be doing wrong, or what do I need to do to get the needed result.

Thank you in advance =) !

angular 7 - missing peer dependency

Currently on Angular: 7.2.15
I get the warning
npm WARN [email protected] requires a peer of @angular/common@^6.0.0-rc.0 || ^6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/core@^6.0.0-rc.0 || ^6.0.0 but none is installed. You must install peer dependencies yourself.

Input focus stops working if data is null or empty

Reproduction:

  1. Add inputFocused handler.
  2. Set data to []
  3. Focus input. inputFocused executed
  4. Click outside.
  5. Focus input. inputFocused is not executed.

Expected: focus handler to be executed every time input is focused.

According to source
https://github.com/gmerabishvili/angular-ng-autocomplete/blob/master/projects/autocomplete-lib/src/lib/autocomplete/autocomplete.component.ts#L449
isFocused is reset only in one place - handleClose. But if data is null, there is nothing to close and component is staying "focussed".

Include accent folding inside auto complete

Hi,

The data contains accents and the user might search without the accent for some text.

I have this method to search a pattern inside a list of string without the accent

`private searchFromArray(arr, regex) {

    let matches = [], i;
    regex = this.removeAccent(regex.toLowerCase());
    if (regex.length < 3)
        return matches;
    for (i = 0; i < arr.length; i++) {
        if (this.removeAccent(arr[i].toLowerCase())
            .indexOf(regex) != -1) {
            matches.push(arr[i]);
        }
    }
    return matches;
};

private removeAccent(str: string) {
    return str.normalize('NFD').replace(/[\u0300-\u036f]/g, "");
}`

Nevertheless, I don't see how to plug it to your component.

When I plug to (inputChanged)='onChangeSearch($event)' I don't have the option to return the list of filtered values.

How can I do it please

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.