GithubHelp home page GithubHelp logo

ng2-ui / auto-complete Goto Github PK

View Code? Open in Web Editor NEW
279.0 22.0 123.0 15.37 MB

Angular Auto Complete component and directive

Home Page: https://ng2-ui.github.io/dist/#/auto-complete

License: MIT License

TypeScript 80.81% HTML 12.36% JavaScript 4.59% SCSS 2.23%

auto-complete's Introduction

auto-complete

npm npm npm

IMPORTANT: HELP NEEDED

The project need your help, any help for fixing bugs and improvements are welcome! GitHub issues

Install

  1. install @ngui/auto-complete

     $ npm install @ngui/auto-complete --save
    
  2. add map and packages to your systemjs.config.js unless you are using webpack

     map['@ngui/auto-complete'] = 'node_modules/@ngui/auto-complete/dist/auto-complete.umd.js';
    
  3. import NguiAutoCompleteModule to your AppModule

     import { NguiAutoCompleteModule } from '@ngui/auto-complete';
    
     @NgModule({
       imports: [BrowserModule, FormsModule, NguiAutoCompleteModule],
       declarations: [AppComponent],
       providers: [HTTP_PROVIDERS],
       bootstrap: [ AppComponent ]
     })
     export class AppModule { }
    

Usage it in your code

    <input auto-complete [(ngModel)]="myData" [source]="mySource" />

For full example, please check test directory to see the example of;

  • systemjs.config.js
  • app.module.ts
  • and app.component.ts.

Demo

You can look at different show cases for it here as Component or Directive.

attributes

All options are optional except ngModel and source

  • ngModel, any, variable that autocomplete result is assigned to

  • source, array or string, required. data source for dropdown list

  • auto-complete-placeholder, string, autocomplete input guide text

  • value-formatter, string or function variable name, custom value formatting function. e.g. (id) value, 'myValueFormatter.

       myValueFormatter(data: any): string {
          return `(${data[id]}) ${data[value]}`;
        }
    
  • list-formatter, string or function variable name, custom list formatting function. e.g. (key) name, myListFormatter.

       myListFormatter(data: any): string {
          return `(${data[key]}) ${data[name]}`;
        }
    
  • path-to-data, string, e.g., data.myList, path to array data in http response

  • min-chars, number, when source is remote data, the number of character to see drop-down list

  • display-property-name, string, key name of text to show. default is value

  • select-value-of, string, when selected, return the value of this key as a selected item

  • blank-option-text, string, guide text to allow empty value to be selected as in empty value of option tag.

  • no-match-found-text, string, guide text to show no result found.

  • valueChanged / ngModelChange, callback function that is executed when a new drop-down is selected. e.g. (valueChanged)="myCallback($event)"

  • customSelected callback function that is executed when a value selected not included in drop-down, so it will return the keyword used. e.g. (customSelected)="customCallback($event)"

  • loading-text, text to be displayed when loading. Default, "Loading"

  • loading-template, html markup that is to be rendered when loading. Default, null

  • accept-user-input boolean, if false and does not match to source given, it goes back to the original value selected., If you don't event want user to type any, please use readonly="readonly" to force user to select only from list. Default is true

  • max-num-list number, maximum number of drop down list items. Default, unlimited

  • tab-to-select boolean, if true, pressing Tab will set the value from the selected item before focus leaves the control. Default is true

  • select-on-blur boolean, if true, blur event will set the value from the selected item before focus leaves the control. Default is false

  • match-formatted boolean, if true, keyword will be matched against list values formatted with list-formatter, instead of raw objects. Default is false

  • auto-select-first-item, boolean, if true, the first item of the list is automatically selected, if false, user must select manually an item. Default is false

  • open-on-focus, boolean, if false drop down won't open on a focus event, . Default is true

  • close-on-focusout, boolean, if false drop down will close on a focusout event, . Default is true

  • re-focus-after-select property, boolean, if false an auto focus behavior after select (example: custom value on blur event or issue #276) is disabled . Default is true

  • autocomplete, boolean, default false, if true remove the attribute autocomplete="off" of the input.

  • header-item-template, html markup to optionally create a non-selectable header row above the list of results. Default, null

  • ignore-accents, boolean, default true, if false user input must match exactly with source given, including accents or diacritics

Below are plunks for different scenarios:

Template Driven Forms

Reactive Forms

Material Design

Observable Source

List Formatter Example

Contributors are welcomed

This module is only improved and maintained by contributors like you;

As a contributor, it's NOT required to be skilled in Javascript nor Angular. You can contribute to the following;

  • Updating README.md
  • Making more and clearer comments
  • Answering issues and building FAQ
  • Documentation
  • Translation

In result of your active contribution, you will be listed as a core contributor on https://ng2-ui.github.io, and a member of ng2-ui too.

If you are interested in becoming a contributor and/or a member of ng-ui, please send me email to allenhwkim AT gmail.com with your github id.

For Developers

To start

$ git clone https://github.com/ng2-ui/auto-complete.git
$ cd auto-complete
$ npm install
$ npm build-lib:watch

$ # On different instance

$ npm start

To publish

$ npm build-lib:prod
$ cd dist
$ npm publish

List of available npm tasks

  • npm run : List all available tasks
  • npm start: Run demo directory for development using @angular/cli with port 4200
  • npm run lint: Lint TypeScript code
  • npm run build-lib:watch: Build library in live watch mode for development
  • npm run build-lib:prod: Build library for publish using view engine (not Ivy renderer)

auto-complete's People

Contributors

allenhwkim avatar almothafar avatar anysite avatar bnjjj avatar boban100janovski avatar bobfleischman avatar deerboy avatar dependabot[bot] avatar dninomiya avatar ednjv avatar faddiv avatar fraserdeans avatar georgesokolovsky avatar gerardobot avatar herobart avatar johnrayner avatar kevinhoelscher avatar koktaildotcom avatar lemarsu avatar mattarau avatar mlamtw avatar ndcunningham avatar rsaenen avatar shadowmanu avatar smitthakkar96 avatar svitlychnyi avatar webcat12345 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

auto-complete's Issues

When pressing enter with empty list it throws error

I fond out that if you press enter when no item is shown it throws an error.

How to reproduce:

  1. Start typing something that doesn't return any result.
  2. When an empty list is shown, press Enter.
  3. An error is thrown.

plunker example current is not working

The plunker example defined in the documentation is not working

TypeError: Zone.assertZonePatched is not a function
NgZoneImpl@https://npmcdn.com/@angular/core/bundles/core.umd.js:6197:13 
NgZone@https://npmcdn.com/@angular/core/bundles/core.umd.js:6346:30

Creates an input inside an input ??

Hi, Im trying to use your library and I get this behavior,
when just pasting your code

<input auto-complete [(ngModel)]="myData" [source]="mySource" />

Into my html template I get this as the end result:

image

Which is an input witin an input, this makes things really difficult when I use a styled input like in this picture:

image

As you can see, this is really awkward,

Limit list items

How can I limit the number of items to show (with scrollable bar)? Is it possible?

error if i dont use input element

Hello,
Since i'm using angular2 material, it doesnt use regular input field so i have to use <md-input ...>
but as soon i click on the input i see the following error.

            <md-input auto-complete
                    [(ngModel)]="myData"
                    placeholder="Enter Address(min. 2 chars)"
                    [source]="googleGeoCode"
                    display-property-name="formatted_address"
                    path-to-data="results"
                    [ngModelOptions]="{standalone: true}"
                    min-chars="2"></md-input> {{model4 | json}}<br/><br/>
EXCEPTION: TypeError: Cannot read property 'instance' of undefinedBrowserDomAdapter.logError @ browser_adapter.js:85BrowserDomAdapter.logGroup @ browser_adapter.js:95ExceptionHandler.call @ exception_handler.js:66next @ application_ref.js:348schedulerFn @ async.js:89SafeSubscriber.__tryOrUnsub @ Subscriber.js:225SafeSubscriber.next @ Subscriber.js:174Subscriber._next @ Subscriber.js:124Subscriber.next @ Subscriber.js:88Subject._finalNext @ Subject.js:128Subject._next @ Subject.js:120Subject.next @ Subject.js:77EventEmitter.emit @ async.js:77onError @ ng_zone.js:124onHandleError @ ng_zone_impl.js:75ZoneDelegate.handleError @ zone.js:336Zone.runTask @ zone.js:268ZoneTask.invoke @ zone.js:433
browser_adapter.js:85 STACKTRACE:BrowserDomAdapter.logError @ browser_adapter.js:85ExceptionHandler.call @ exception_handler.js:68next @ application_ref.js:348schedulerFn @ async.js:89SafeSubscriber.__tryOrUnsub @ Subscriber.js:225SafeSubscriber.next @ Subscriber.js:174Subscriber._next @ Subscriber.js:124Subscriber.next @ Subscriber.js:88Subject._finalNext @ Subject.js:128Subject._next @ Subject.js:120Subject.next @ Subject.js:77EventEmitter.emit @ async.js:77onError @ ng_zone.js:124onHandleError @ ng_zone_impl.js:75ZoneDelegate.handleError @ zone.js:336Zone.runTask @ zone.js:268ZoneTask.invoke @ zone.js:433
browser_adapter.js:85 TypeError: Cannot read property 'instance' of undefined
    at AutoCompleteDirective.styleAutoCompleteDropdown (http://localhost:3000/main.bundle.js:1816:47)
    at ZoneDelegate.invokeTask (http://localhost:3000/polyfills.bundle.js:16485:38)
    at Object.onInvokeTask (http://localhost:3000/vendor.bundle.js:47232:41)
    at ZoneDelegate.invokeTask (http://localhost:3000/polyfills.bundle.js:16484:43)
    at Zone.runTask (http://localhost:3000/polyfills.bundle.js:16385:48)
    at ZoneTask.invoke (http://localhost:3000/polyfills.bundle.js:16553:34)
  -------------   Elapsed: 19 ms; At: Thu Sep 01 2016 01:03:40 GMT-0500 (CDT)   -------------  
    at Object.onScheduleTask (http://localhost:3000/polyfills.bundle.js:16058:23)
    at ZoneDelegate.scheduleTask (http://localhost:3000/polyfills.bundle.js:16462:50)
    at Zone.scheduleMacroTask (http://localhost:3000/polyfills.bundle.js:16402:40)
    at http://localhost:3000/polyfills.bundle.js:17461:30
    at setTimeout (eval at createNamedFn (http://localhost:3000/polyfills.bundle.js:1:0), <anonymous>:3:37)
    at AutoCompleteDirective.showAutoCompleteDropdown (http://localhost:3000/main.bundle.js:1875:9)
    at DebugAppView._View_Signup2._handle_click_11_1 (Signup.ngfactory.js:1998:49)
    at http://localhost:3000/vendor.bundle.js:65392:24
    at http://localhost:3000/vendor.bundle.js:21964:36
    at http://localhost:3000/vendor.bundle.js:33352:111
    at ZoneDelegate.invoke (http://localhost:3000/polyfills.bundle.js:16452:29)
    at Object.onInvoke (http://localhost:3000/vendor.bundle.js:47241:41)
    at ZoneDelegate.invoke (http://localhost:3000/polyfills.bundle.js:16451:35)
    at Zone.runGuarded (http://localhost:3000/polyfills.bundle.js:16359:48)
    at NgZoneImpl.runInnerGuarded (http://localhost:3000/vendor.bundle.js:47274:78)
    at NgZone.runGuarded (http://localhost:3000/vendor.bundle.js:31929:73)
    at HTMLElement.outsideHandler (http://localhost:3000/vendor.bundle.js:33352:79)
    at ZoneDelegate.invokeTask (http://localhost:3000/polyfills.bundle.js:16485:38)
    at Zone.runTask (http://localhost:3000/polyfills.bundle.js:16385:48)
    at HTMLElement.ZoneTask.invoke (http://localhost:3000/polyfills.bundle.js:16553:34)

use with formControlName instead of ngModel?

First of all thank you for your auto-complete. really useful!!!!

However, I created the form in my app using the formControl so with input, I can not use ngModel but formControlName.

When I select an item from the dropdown, it's not updated on the input, still show whatever the initial formControlName were.

Is there anyway to make the autocomplete work with formControlName?

(change) event is not triggered after selecting an options

I have to following code as an example:
<input type="text" class="form-control" placeholder="Partner" auto-complete [source]="filters.merchants" (change)="filterOrders('merchant.id', $event.target.value)"/>

In my component I have a console.log in the filterOrders function, but it isn't triggered.
Seems like the (click) gets removed when creating the ng-auto-complete element?

Problems with OPTIONS request(desapeared)

I have updated autocomplete module to 0.2.0 versions from 0.1.6 and i haven't seen sending OPTIONS request to server, i can't get data from server. Could you check and fix if it posible. At 0.1.6 version it has worked perfect

how to use "value-changed" and "value-property-name" ?

value-changed, function variable name, callback function that is executed when dropdown is selected. e.g. myCallback, not myCallback

I don't see the different between the e.g and the not.

Can I use it like (value-changed)="myFunction(id)" or it's just function name only, no parameters sending with it is accepted?

And for value-property-name, what ever key name I assigned to this, it still bind the whole object to the ngModel. I just want to bind the key buildingID, not the whole object.

value-property-name="buildingID"

Inject Authentication Credentials into the request header of source URL

I have a WebAPI method that I call to get my autocomplete list. This method is protected by OAUTH2 authentication, so in order to call it I need to inject authentication credentials into the request header (to be specific, i need to add a Bearer token as an Authorization header) but ng2-auto-complete does not provide a way to do this. (unless I'm missing something?).

Would it be possible to provide a mechanism to modify http GET request headers before calling the URL?

(I have worked around this issue for now by removing the authorization requirement for my WebAPI method, so it's not a show-stopper for myself right now. However, I can see it being a show-stopper for other people).

Parameter 'event' implicitly has an 'any' type

My project's typescript transpilation fails due to the following error:

node_modules/ng2-auto-complete/dist/auto-complete.directive.ts(92,31): error TS7006: Parameter 'event' implicitly has an 'any' type.

Can you please remedy this by explicitly declaring a type? (event?: any)

Input is cleared on focus/click

This behavior of cleaning the input in focus seems a little odd to me cause, in my opinion, if the goals is to mimic the input behavior extending it with new features, the text in the input should be keeped like in default input component.

Another issue that this behavior creates is that if you click in the input and the shown value is changed to empty string, the value is not propagated to the ngModel, leaving the component in a corrupted status if you leave the component without type anything.

I have forked the repo and changed to behave like a simple input field, and soon I'll submit a pull request.

I really like this component and hope you can accept this PR, even tough I know that this change the actual default behavior.

Dropdown psotioning and size

Is it possible to position the dropdown dynamically according the available height of the container (if the available height is less then dropdown should be displayed on top of the text box)?
It would have been better if there is property to specify the the max height for the dropdown.

[value-changed] gets executed a 1000 times

I implemented something like this:

  <input
    auto-complete
    [(ngModel)]="result"
    [source]="states"
    [display-property-name]="'name'"
    [value-changed]="search()"
    [min-chars]="3"
    class="form-control"
    placeholder="Search...">

The functionsearch()gets executed a 1000 times immediately. It should only be executed when I type or remove a letter, right?

The search function should update the source "states" every time I type in a letter.

Thanks for your support in advance!

Junus Ergin

Support for Textarea

Hey guys,

is there any support forseen for textarea auto-complete support or should I contribute to the project?

Best Regards,

Stefan

Overwrite "Loading" text

Is there any way to overwrite the text "loading" while fetching data with remote source as HTTP URI string?

Default value for ngModel

The fix for initial value is perfect, but the [(ngModel)] do not reflect the display value when the model is changed manully

Bind source to Observable

Hi, guys.

Is it possible to bind the source property to an Observable? It seems it only supports array or string.

My use case: I have a method in a service that does some async processing and then returns an Observable array. I want to bind the auto-complete to this method.

Thanks!

can't shift+tab to a previous field

When you you tab or click on the autocomplete field if you try to shift+tab to go to the previous field it just resets the autocomplete search, presumably because it's tabbing back to the initial autocomplete field and then creating a new autocomplete input each time.

Can't bind to 'source' since it isn't a known property of 'input'

Hi,

Thanks for the job,

I tried to integrate the auto-complete, but I got this error :

Can't bind to 'source' since it isn't a known property of 'input'

 <input auto-complete formControlName="itemControl" [(ngModel)]="itemSelected" [source]="items" placeholder="Select an item"
      />

How can I do to ignore this error?

Thanks

"BrowserModule has already been loaded"

If you import Ng2AutoCompleteModule into an NgModule that already imports BrowserModule (which will be pretty much any angular2 app). You get this error message, because i believe BrowserModule can only be imported once.

It seems like a better idea for Ng2AutoCompleteModule to import CommonModule instead.

The current design pretty much prohibits you from importing Ng2AutoCompleteModule into any child module.

The point i'm trying to make is confirmed in this stackoverflow post (look at accepted answer):
http://stackoverflow.com/questions/39414231/angular2-rc6-importing-browsermodule-in-my-submodules

thoughts?

Webpack integration

My question may be silly, but the readme.MD only explains how to use this directive on SystemJS, and since the angular-cli is using webpack to generate the builds I have no clue on how to use this directive.

I tried to:

  1. Install it using npm install ng2-auto-complete --save and importing on my module
    Results on module not found
  2. Add the mapping on angular-cli.json to "../node_modules/ng2-auto-complete/dist/ng2-auto-complete.umd.js"
    It throws an exception Uncaught TypeError: Cannot read property 'Injectable' of undefined

So, could you please help with the usage on Webpack ? (Once I understands how it works I can send a PR to update the readme)

Cannot search for a result when autocomplete does not return any value

When I type in the search box, I expect that if no match is found by auto-complete, I can still launch a search with the string I typed. This does not seem possible here, as ngModel is only updated when I select an item in the list.

I would expect the component to store what I typed, in order to be able to launch a "normal" search (like if autocomplete did not exist).

Decouple the "keyword" word

Hello,
I recently tried this auto-complete out, and I must give you fair warning, I am a total Angular2 noob, I tried out a few auto-complete to get one working, but I think this is pretty cool, only one slight issue I feel I have. My data source is a GET http. so I followed the google api example, and it works, but I feel its rather annoying to use :keyword as a fixed string, maybe you can make this some sort of a variable, that can be defined in the template or something more flexible.
Also if its already possible, would love to know how.

Cheers!

PS: I am using the latest (0.7.3)

error on import

Hello,
i am getting this error when i try to import the module.

code:

import {AutoCompleteDirective} from "ng2-auto-complete";
@Component({
    templateUrl: ....
    directives: [REACTIVE_FORM_DIRECTIVES, AutoCompleteDirective],
....
})

error

/project/node_modules/ng2-auto-complete/dist/auto-complete.directive.ts:1
import {
^
ParseError: 'import' and 'export' may appear only with 'sourceType: module'

Default value for ngModel

How can I specify the default/initial ngModel values? Now if I initialize the model object, I'm getting "[object] [object]"

[(ngModel)] binding to object gets corrupted

I am using ng-auto-complete v0.11.4, with angular 2.0.0, as follows:

<input ng2-auto-complete name="row{{row.DisplayOrder}}Task2" 
[source]="getTaskListFunction(row)"
[(ngModel)]="row.TaskListItem"
min-chars="2"
[list-formatter]="taskAutoCompleteFormatter"
value-property-name="Id"
display-property-name="Value"
/>

I am defining this element inside a table of repeating tr rows using *ngFor. The table is contained within a form.

getTaskListFunction() returns a function, and this function, in turn, returns an Observable<TimesheetTaskListItem[]>.

row.TaskListItem is an instance of TimesheetTaskListItem object, defined as

class TimesheetTaskListItem { Id: number; Value: string; }

Everything works great, up to the point where I submit my form (calling WebAPI). Until I submit the form, the two-way binding to row.TaskListItem works as expected in that when first rendering the input element it shows the 'Value' property of the bound object, and when I select a different object from the auto-complete list it will correctly replace the instance referenced by row.TaskListItem with the object selected in the list and display the 'Value' property of this new object.

The binding gets screwed once I submit the form (to a WebAPI operation). After making this submission, the binding displays the contents of the input box as "[object Object]", which I interpret to mean that it is no longer respecting the display-property-name attribute. If I reload the data that my form is bound to then the binding remains corrupted, even if I load data for a different record.

Note that when I submit the form, I do not modify the row.TaskListItem object in any way and I do not modify any attributes of the input element.

I have tried my best to isolate where in my code or auto-complete's code this corruption first occurs but I am unable to diagnose any further than saving it is occurring at some point during/after the form submission. As for the resolution, I can only assume that the fix lies:

  1. I'm doing something wrong in my definition of input element.
  2. There is something wrong with the two-way binding in ng2-auto-complete.
  3. This is a more general bug with angular2.

Have you got any ideas about the cause of this problem, and if not a fix, then any ideas on a workaround.

Thanks in advance

Exception thrown when tried to include the "ng2-auto-complete" as nested component

I created 'AnalysisPickerComponent' which contains "ng2-auto-complete". Then I tried to include the 'AnalysisPickerComponent' inside my 'HomeComponent'.

Component nesting order: 'HomeComponent' -> 'AnalysisPickerComponent' -> 'ng2-auto-complete'

EXCEPTION: Error: Uncaught (in promise): Unexpected directive value 'undefined' on the View of component 'AnalysisPickerComponent'

Questions

Hi,

I have a few question:

  • How can I use a method that returns an Observable as the source? Is there an example?
  • How can I customize the list? I guess '.ng2-auto-complete ul li'.

Autocomplete based on first letter?

Would it somehow be possible to get the auto complete to do the search based on first letter? I mean I have hundreds of data, so it is not so ideal when the search is not based on first letter. Tried looking into the package and do some modifications myself on the regex, but didn't succeed. Keep in bind that I'm a newbie, hehhe.

Any help would be appreciated!

ng2-auto-complete/dist/auto-complete.component.ts - any type

Hi. You are write good autocomplete. Please, could u set up type of variable
in file - ng2-auto-complete/dist/auto-complete.component.ts
on line 177 ( return function(callback: any, ms: any) )
asap if it possible, because my application cannot run without it

angular 2 final intergration?

How to make this work with Angular 2 final (2.0.1) ? thank you!

I got an error when import the module in AppModule:

screen shot 2016-09-27 at 12 43 40

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.