├── src
├── assets
│ ├── .gitkeep
│ └── countries.json
├── app
│ ├── app.component.css
│ ├── app.service.ts
│ ├── app.component.ts
│ ├── app.module.ts
│ ├── app.component.spec.ts
│ └── app.component.html
├── favicon.ico
├── environments
│ ├── environment.prod.ts
│ └── environment.ts
├── styles.css
├── tsconfig.app.json
├── tsconfig.spec.json
├── browserslist
├── tslint.json
├── main.ts
├── index.html
├── test.ts
├── karma.conf.js
└── polyfills.ts
├── .vscode
└── settings.json
├── .prettierignore
├── db.json
├── .prettierrc
├── projects
└── ngx-mat-typeahead
│ ├── src
│ ├── lib-assets
│ │ └── countries.json
│ ├── public_api.ts
│ ├── lib
│ │ ├── ngx-mat-typeahead.module.ts
│ │ ├── ngx-mat-typeahead-util.ts
│ │ ├── ngx-mat-typeahead.directive.spec.ts
│ │ ├── ngx-mat-typeahead.directive.ts
│ │ ├── ngx-mat-typeahead.service.spec.ts
│ │ └── ngx-mat-typeahead.service.ts
│ └── test.ts
│ ├── ng-package.prod.json
│ ├── ng-package.json
│ ├── tsconfig.spec.json
│ ├── tslint.json
│ ├── CHANGELOG.md
│ ├── package.json
│ ├── tsconfig.lib.json
│ ├── karma.conf.js
│ ├── LICENSE
│ └── README.md
├── e2e
├── src
│ ├── app.po.ts
│ └── app.e2e-spec.ts
├── tsconfig.e2e.json
└── protractor.conf.js
├── .editorconfig
├── tsconfig.json
├── .gitignore
├── CHANGELOG.md
├── LICENSE
├── package.json
├── tslint.json
├── angular.json
└── README.md
/src/assets/.gitkeep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | }
--------------------------------------------------------------------------------
/src/app/app.component.css:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/.prettierignore:
--------------------------------------------------------------------------------
1 | package.json
2 | package-lock.json
3 | yarn.lock
4 | /dist
5 | README.md
6 |
--------------------------------------------------------------------------------
/src/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mrsan22/NgxMatTypeahead/HEAD/src/favicon.ico
--------------------------------------------------------------------------------
/src/environments/environment.prod.ts:
--------------------------------------------------------------------------------
1 | export const environment = {
2 | production: true
3 | };
4 |
--------------------------------------------------------------------------------
/db.json:
--------------------------------------------------------------------------------
1 | {
2 | "countries": ["United States", "United Kingdom", "China", "Japan", "India", "Russia", "Canada", "Brazil"]
3 | }
4 |
--------------------------------------------------------------------------------
/src/styles.css:
--------------------------------------------------------------------------------
1 | /* You can add global styles to this file, and also import other style files */
2 |
3 | body {
4 | margin: 20px;
5 | }
6 |
--------------------------------------------------------------------------------
/src/assets/countries.json:
--------------------------------------------------------------------------------
1 | {
2 | "countries": ["United States", "United Kingdom", "China", "Japan", "India", "Russia", "Canada", "Brazil"]
3 | }
4 |
--------------------------------------------------------------------------------
/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "printWidth": 120,
3 | "singleQuote": true,
4 | "useTabs": false,
5 | "tabWidth": 2,
6 | "semi": true,
7 | "bracketSpacing": true
8 | }
9 |
--------------------------------------------------------------------------------
/projects/ngx-mat-typeahead/src/lib-assets/countries.json:
--------------------------------------------------------------------------------
1 | {
2 | "countries": ["United States", "United Kingdom", "China", "Japan", "India", "Russia", "Canada", "Brazil"]
3 | }
4 |
--------------------------------------------------------------------------------
/projects/ngx-mat-typeahead/ng-package.prod.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "../../node_modules/ng-packagr/ng-package.schema.json",
3 | "dest": "../../dist/ngx-mat-typeahead",
4 | "lib": {
5 | "entryFile": "src/public_api.ts"
6 | }
7 | }
--------------------------------------------------------------------------------
/projects/ngx-mat-typeahead/ng-package.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "../../node_modules/ng-packagr/ng-package.schema.json",
3 | "dest": "../../dist/ngx-mat-typeahead",
4 | "deleteDestPath": false,
5 | "lib": {
6 | "entryFile": "src/public_api.ts"
7 | }
8 | }
--------------------------------------------------------------------------------
/projects/ngx-mat-typeahead/src/public_api.ts:
--------------------------------------------------------------------------------
1 | /*
2 | * Public API Surface of ngx-mat-typeahead
3 | */
4 |
5 | export * from './lib/ngx-mat-typeahead.service';
6 | export * from './lib/ngx-mat-typeahead.directive';
7 | export * from './lib/ngx-mat-typeahead.module';
8 |
--------------------------------------------------------------------------------
/src/tsconfig.app.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../tsconfig.json",
3 | "compilerOptions": {
4 | "outDir": "../out-tsc/app",
5 | "module": "es2015",
6 | "types": []
7 | },
8 | "exclude": [
9 | "src/test.ts",
10 | "**/*.spec.ts"
11 | ]
12 | }
13 |
--------------------------------------------------------------------------------
/e2e/src/app.po.ts:
--------------------------------------------------------------------------------
1 | import { browser, by, element } from 'protractor';
2 |
3 | export class AppPage {
4 | navigateTo() {
5 | return browser.get('/');
6 | }
7 |
8 | getParagraphText() {
9 | return element(by.css('mat-ta-root h1')).getText();
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/e2e/tsconfig.e2e.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../tsconfig.json",
3 | "compilerOptions": {
4 | "outDir": "../out-tsc/app",
5 | "module": "commonjs",
6 | "target": "es5",
7 | "types": [
8 | "jasmine",
9 | "jasminewd2",
10 | "node"
11 | ]
12 | }
13 | }
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | # Editor configuration, see http://editorconfig.org
2 | root = true
3 |
4 | [*]
5 | charset = utf-8
6 | indent_style = space
7 | indent_size = 2
8 | insert_final_newline = true
9 | trim_trailing_whitespace = true
10 |
11 | [*.md]
12 | max_line_length = off
13 | trim_trailing_whitespace = false
14 |
--------------------------------------------------------------------------------
/projects/ngx-mat-typeahead/tsconfig.spec.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../../tsconfig.json",
3 | "compilerOptions": {
4 | "outDir": "../../out-tsc/spec",
5 | "types": [
6 | "jasmine",
7 | "node"
8 | ]
9 | },
10 | "files": [
11 | "src/test.ts"
12 | ],
13 | "include": [
14 | "**/*.spec.ts",
15 | "**/*.d.ts"
16 | ]
17 | }
18 |
--------------------------------------------------------------------------------
/e2e/src/app.e2e-spec.ts:
--------------------------------------------------------------------------------
1 | import { AppPage } from './app.po';
2 |
3 | describe('workspace-project App', () => {
4 | let page: AppPage;
5 |
6 | beforeEach(() => {
7 | page = new AppPage();
8 | });
9 |
10 | it('should display welcome message', () => {
11 | page.navigateTo();
12 | expect(page.getParagraphText()).toEqual('Welcome to mat-ta!');
13 | });
14 | });
15 |
--------------------------------------------------------------------------------
/src/tsconfig.spec.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../tsconfig.json",
3 | "compilerOptions": {
4 | "outDir": "../out-tsc/spec",
5 | "module": "commonjs",
6 | "types": [
7 | "jasmine",
8 | "node"
9 | ]
10 | },
11 | "files": [
12 | "test.ts",
13 | "polyfills.ts"
14 | ],
15 | "include": [
16 | "**/*.spec.ts",
17 | "**/*.d.ts"
18 | ]
19 | }
20 |
--------------------------------------------------------------------------------
/src/browserslist:
--------------------------------------------------------------------------------
1 | # This file is currently used by autoprefixer to adjust CSS to support the below specified browsers
2 | # For additional information regarding the format and rule options, please see:
3 | # https://github.com/browserslist/browserslist#queries
4 | # For IE 9-11 support, please uncomment the last line of the file and adjust as needed
5 | > 0.5%
6 | last 2 versions
7 | Firefox ESR
8 | not dead
9 | # IE 9-11
--------------------------------------------------------------------------------
/src/tslint.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../tslint.json",
3 | "rules": {
4 | "directive-selector": [
5 | true,
6 | "attribute",
7 | "mat-ta",
8 | "camelCase"
9 | ],
10 | "component-selector": [
11 | true,
12 | "element",
13 | "mat-ta",
14 | "kebab-case"
15 | ]
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/main.ts:
--------------------------------------------------------------------------------
1 | import { enableProdMode } from '@angular/core';
2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
3 |
4 | import { AppModule } from './app/app.module';
5 | import { environment } from './environments/environment';
6 |
7 | if (environment.production) {
8 | enableProdMode();
9 | }
10 |
11 | platformBrowserDynamic().bootstrapModule(AppModule)
12 | .catch(err => console.log(err));
13 |
--------------------------------------------------------------------------------
/projects/ngx-mat-typeahead/tslint.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../../tslint.json",
3 | "rules": {
4 | "directive-selector": [
5 | true,
6 | "attribute",
7 | "NgxMat",
8 | "camelCase"
9 | ],
10 | "component-selector": [
11 | true,
12 | "element",
13 | "NgxMat",
14 | "kebab-case"
15 | ]
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/projects/ngx-mat-typeahead/src/lib/ngx-mat-typeahead.module.ts:
--------------------------------------------------------------------------------
1 | import { HttpClientModule } from '@angular/common/http';
2 | import { NgModule } from '@angular/core';
3 | import { NgxMatTypeaheadDirective } from './ngx-mat-typeahead.directive';
4 |
5 | @NgModule({
6 | imports: [HttpClientModule],
7 | declarations: [NgxMatTypeaheadDirective],
8 | exports: [NgxMatTypeaheadDirective]
9 | })
10 | export class NgxMatTypeaheadModule {}
11 |
--------------------------------------------------------------------------------
/projects/ngx-mat-typeahead/src/lib/ngx-mat-typeahead-util.ts:
--------------------------------------------------------------------------------
1 | export enum Key {
2 | Backspace = 8,
3 | Tab = 9,
4 | Enter = 13,
5 | Shift = 16,
6 | Escape = 27,
7 | ArrowLeft = 37,
8 | ArrowRight = 39,
9 | ArrowUp = 38,
10 | ArrowDown = 40
11 | }
12 | export enum validHttpMethods {
13 | 'GET' = 'get',
14 | 'POST' = 'post',
15 | 'PUT' = 'put',
16 | 'PATCH' = 'patch',
17 | 'DELETE' = 'delete',
18 | 'REQUEST' = 'request'
19 | }
20 |
--------------------------------------------------------------------------------
/src/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | MatTypeaheadLibrary
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/src/app/app.service.ts:
--------------------------------------------------------------------------------
1 | import { HttpClient } from '@angular/common/http';
2 | import { Injectable } from '@angular/core';
3 | import { Observable } from 'rxjs';
4 | import { map } from 'rxjs/operators';
5 |
6 | @Injectable({
7 | providedIn: 'root'
8 | })
9 | export class AppService {
10 | constructor(private http: HttpClient) {}
11 |
12 | getCountries(): Observable> {
13 | return this.http.get>('../assets/countries.json').pipe(
14 | map(data => {
15 | return data['countries'];
16 | })
17 | );
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compileOnSave": false,
3 | "compilerOptions": {
4 | "baseUrl": "./",
5 | "outDir": "./dist/out-tsc",
6 | "sourceMap": true,
7 | "declaration": false,
8 | "moduleResolution": "node",
9 | "emitDecoratorMetadata": true,
10 | "experimentalDecorators": true,
11 | "target": "es5",
12 | "typeRoots": [
13 | "node_modules/@types"
14 | ],
15 | "lib": [
16 | "es2017",
17 | "dom"
18 | ],
19 | "paths": {
20 | "NgxMatTypeahead": [
21 | "dist/ngx-mat-typeahead"
22 | ]
23 | }
24 | }
25 | }
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # See http://help.github.com/ignore-files/ for more about ignoring files.
2 |
3 | # compiled output
4 | /dist
5 | /tmp
6 | /out-tsc
7 |
8 | # dependencies
9 | /node_modules
10 |
11 | # IDEs and editors
12 | /.idea
13 | .project
14 | .classpath
15 | .c9/
16 | *.launch
17 | .settings/
18 | *.sublime-workspace
19 |
20 | # IDE - VSCode
21 | .vscode/*
22 | !.vscode/settings.json
23 | !.vscode/tasks.json
24 | !.vscode/launch.json
25 | !.vscode/extensions.json
26 |
27 | # misc
28 | /.sass-cache
29 | /connect.lock
30 | /coverage
31 | /libpeerconnection.log
32 | npm-debug.log
33 | yarn-error.log
34 | testem.log
35 | /typings
36 |
37 | # System Files
38 | .DS_Store
39 | Thumbs.db
40 |
--------------------------------------------------------------------------------
/src/environments/environment.ts:
--------------------------------------------------------------------------------
1 | // This file can be replaced during build by using the `fileReplacements` array.
2 | // `ng build ---prod` replaces `environment.ts` with `environment.prod.ts`.
3 | // The list of file replacements can be found in `angular.json`.
4 |
5 | export const environment = {
6 | production: false
7 | };
8 |
9 | /*
10 | * In development mode, to ignore zone related error stack frames such as
11 | * `zone.run`, `zoneDelegate.invokeTask` for easier debugging, you can
12 | * import the following file, but please comment it out in production mode
13 | * because it will have performance impact when throw error
14 | */
15 | // import 'zone.js/dist/zone-error'; // Included with Angular CLI.
16 |
--------------------------------------------------------------------------------
/src/test.ts:
--------------------------------------------------------------------------------
1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files
2 |
3 | import 'zone.js/dist/zone-testing';
4 | import { getTestBed } from '@angular/core/testing';
5 | import {
6 | BrowserDynamicTestingModule,
7 | platformBrowserDynamicTesting
8 | } from '@angular/platform-browser-dynamic/testing';
9 |
10 | declare const require: any;
11 |
12 | // First, initialize the Angular testing environment.
13 | getTestBed().initTestEnvironment(
14 | BrowserDynamicTestingModule,
15 | platformBrowserDynamicTesting()
16 | );
17 | // Then we find all the tests.
18 | const context = require.context('./', true, /\.spec\.ts$/);
19 | // And load the modules.
20 | context.keys().map(context);
21 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | ## NgxMatTypeahead - v1.0.2 (04/18/2020)
2 |
3 | ### Improvements:
4 |
5 | - Library compatible with Ivy.
6 | - Made the Peer depedency of Angular to version 8.
7 | - Updated ReadMe.
8 |
9 | ## NgxMatTypeahead - v1.0.1 (05/27/2018)
10 |
11 | ### Improvements:
12 |
13 | - Added MIT License.
14 | - Updated README with correct npm installation command for this directive.
15 | - Updated example code under `src/app` to use `ngx-mat-typeahead` module from npm/node_modules.
16 |
17 | ## NgxMatTypeahead - v1.0.0 (05/27/2018)
18 |
19 | ### New Features:
20 |
21 | - A simple typeahead `directive` to be used with Angular Material input and matAutocomplete component. Go through the `README.md` file for detailed features and documentation.
22 |
--------------------------------------------------------------------------------
/projects/ngx-mat-typeahead/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | ## NgxMatTypeahead - v1.0.2 (04/18/2020)
2 |
3 | ### Improvements:
4 |
5 | - Library compatible with Ivy.
6 | - Made the Peer depedency of Angular to version 8.
7 | - Updated ReadMe.
8 |
9 | ## NgxMatTypeahead - v1.0.1 (05/27/2018)
10 |
11 | ### Improvements:
12 |
13 | - Added MIT License.
14 | - Updated README with correct npm installation command for this directive.
15 | - Updated example code under `src/app` to use `ngx-mat-typeahead` module from npm/node_modules.
16 |
17 | ## NgxMatTypeahead - v1.0.0 (05/27/2018)
18 |
19 | ### New Features:
20 |
21 | - A simple typeahead `directive` to be used with Angular Material input and matAutocomplete component. Go through the `README.md` file for detailed features and documentation.
22 |
--------------------------------------------------------------------------------
/projects/ngx-mat-typeahead/src/test.ts:
--------------------------------------------------------------------------------
1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files
2 |
3 | import 'core-js/es7/reflect';
4 | import 'zone.js/dist/zone';
5 | import 'zone.js/dist/zone-testing';
6 | import { getTestBed } from '@angular/core/testing';
7 | import {
8 | BrowserDynamicTestingModule,
9 | platformBrowserDynamicTesting
10 | } from '@angular/platform-browser-dynamic/testing';
11 |
12 | declare const require: any;
13 |
14 | // First, initialize the Angular testing environment.
15 | getTestBed().initTestEnvironment(
16 | BrowserDynamicTestingModule,
17 | platformBrowserDynamicTesting()
18 | );
19 | // Then we find all the tests.
20 | const context = require.context('./', true, /\.spec\.ts$/);
21 | // And load the modules.
22 | context.keys().map(context);
23 |
--------------------------------------------------------------------------------
/projects/ngx-mat-typeahead/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ngx-mat-typeahead",
3 | "version": "1.0.2",
4 | "description":"A simple typeahead directive to be used with Angular Material input and matAutocomplete component.",
5 | "author": "Sanjiv Kumar (mr.san.kumar@gmail.com)",
6 | "repository": {
7 | "type": "git",
8 | "url": "https://github.com/mrsan22/NgxMatTypeahead.git"
9 | },
10 | "bugs": {
11 | "url": "https://github.com/mrsan22/NgxMatTypeahead/issues"
12 | },
13 | "homepage": "https://github.com/mrsan22/NgxMatTypeahead",
14 | "keywords": [
15 | "angular",
16 | "javascript",
17 | "typescript",
18 | "typeahead",
19 | "directive",
20 | "angular-material"
21 | ],
22 | "license": "MIT",
23 | "peerDependencies": {
24 | "@angular/common": "^8.0.0",
25 | "@angular/core": "^8.0.0"
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/e2e/protractor.conf.js:
--------------------------------------------------------------------------------
1 | // Protractor configuration file, see link for more information
2 | // https://github.com/angular/protractor/blob/master/lib/config.ts
3 |
4 | const { SpecReporter } = require('jasmine-spec-reporter');
5 |
6 | exports.config = {
7 | allScriptsTimeout: 11000,
8 | specs: [
9 | './src/**/*.e2e-spec.ts'
10 | ],
11 | capabilities: {
12 | 'browserName': 'chrome'
13 | },
14 | directConnect: true,
15 | baseUrl: 'http://localhost:4200/',
16 | framework: 'jasmine',
17 | jasmineNodeOpts: {
18 | showColors: true,
19 | defaultTimeoutInterval: 30000,
20 | print: function() {}
21 | },
22 | onPrepare() {
23 | require('ts-node').register({
24 | project: require('path').join(__dirname, './tsconfig.e2e.json')
25 | });
26 | jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
27 | }
28 | };
--------------------------------------------------------------------------------
/projects/ngx-mat-typeahead/tsconfig.lib.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../../tsconfig.json",
3 | "compilerOptions": {
4 | "outDir": "../../out-tsc/lib",
5 | "target": "es2015",
6 | "module": "es2015",
7 | "moduleResolution": "node",
8 | "declaration": true,
9 | "sourceMap": true,
10 | "inlineSources": true,
11 | "emitDecoratorMetadata": true,
12 | "experimentalDecorators": true,
13 | "importHelpers": true,
14 | "types": [],
15 | "lib": [
16 | "dom",
17 | "es2015"
18 | ]
19 | },
20 | "angularCompilerOptions": {
21 | "annotateForClosureCompiler": true,
22 | "skipTemplateCodegen": true,
23 | "strictMetadataEmit": true,
24 | "fullTemplateTypeCheck": true,
25 | "strictInjectionParameters": true,
26 | "flatModuleId": "AUTOGENERATED",
27 | "flatModuleOutFile": "AUTOGENERATED"
28 | },
29 | "exclude": [
30 | "src/test.ts",
31 | "**/*.spec.ts"
32 | ]
33 | }
34 |
--------------------------------------------------------------------------------
/src/app/app.component.ts:
--------------------------------------------------------------------------------
1 | import { Component, OnInit } from '@angular/core';
2 | import { FormControl, FormGroup } from '@angular/forms';
3 | import { AppService } from './app.service';
4 | @Component({
5 | selector: 'mat-ta-root',
6 | templateUrl: './app.component.html',
7 | styleUrls: ['./app.component.css']
8 | })
9 | export class AppComponent implements OnInit {
10 | // Paramteres for the input type are defined below. The url is generated using `json-server`.
11 | // Please run your own instance of the json-server to use the the below url.
12 | queryParam = 'q';
13 | url = 'http://localhost:3000/countries';
14 |
15 | constructor(private appService: AppService) {}
16 |
17 | testFormGroup: FormGroup = new FormGroup({ country: new FormControl('') });
18 | countries: Array = [];
19 |
20 | ngOnInit() {
21 | this.appService.getCountries().subscribe(data => (this.countries = data));
22 | }
23 |
24 | getFilteredSuggestions(filteredDataLst: Array) {
25 | this.countries = [...filteredDataLst];
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/app/app.module.ts:
--------------------------------------------------------------------------------
1 | import { HttpClientModule } from '@angular/common/http';
2 | import { NgModule } from '@angular/core';
3 | import { FormsModule, ReactiveFormsModule } from '@angular/forms';
4 | import { MatAutocompleteModule, MatInputModule } from '@angular/material';
5 | import { BrowserModule } from '@angular/platform-browser';
6 | import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
7 | // Local import from projects/ngx-mat-typeahead.
8 | // import { NgxMatTypeaheadModule } from 'NgxMatTypeahead';
9 | // Import from node_modules.
10 | import { NgxMatTypeaheadModule } from 'ngx-mat-typeahead';
11 | import { AppComponent } from './app.component';
12 |
13 | @NgModule({
14 | declarations: [AppComponent],
15 | imports: [
16 | BrowserModule,
17 | BrowserAnimationsModule,
18 | FormsModule,
19 | ReactiveFormsModule,
20 | MatInputModule,
21 | MatAutocompleteModule,
22 | HttpClientModule,
23 | NgxMatTypeaheadModule,
24 | ],
25 | providers: [],
26 | bootstrap: [AppComponent],
27 | })
28 | export class AppModule {}
29 |
--------------------------------------------------------------------------------
/src/karma.conf.js:
--------------------------------------------------------------------------------
1 | // Karma configuration file, see link for more information
2 | // https://karma-runner.github.io/1.0/config/configuration-file.html
3 |
4 | module.exports = function (config) {
5 | config.set({
6 | basePath: '',
7 | frameworks: ['jasmine', '@angular-devkit/build-angular'],
8 | plugins: [
9 | require('karma-jasmine'),
10 | require('karma-chrome-launcher'),
11 | require('karma-jasmine-html-reporter'),
12 | require('karma-coverage-istanbul-reporter'),
13 | require('@angular-devkit/build-angular/plugins/karma')
14 | ],
15 | client: {
16 | clearContext: false // leave Jasmine Spec Runner output visible in browser
17 | },
18 | coverageIstanbulReporter: {
19 | dir: require('path').join(__dirname, '../coverage'),
20 | reports: ['html', 'lcovonly'],
21 | fixWebpackSourcePaths: true
22 | },
23 | reporters: ['progress', 'kjhtml'],
24 | port: 9876,
25 | colors: true,
26 | logLevel: config.LOG_INFO,
27 | autoWatch: true,
28 | browsers: ['Chrome'],
29 | singleRun: false
30 | });
31 | };
--------------------------------------------------------------------------------
/projects/ngx-mat-typeahead/karma.conf.js:
--------------------------------------------------------------------------------
1 | // Karma configuration file, see link for more information
2 | // https://karma-runner.github.io/1.0/config/configuration-file.html
3 |
4 | module.exports = function (config) {
5 | config.set({
6 | basePath: '',
7 | frameworks: ['jasmine', '@angular-devkit/build-angular'],
8 | plugins: [
9 | require('karma-jasmine'),
10 | require('karma-chrome-launcher'),
11 | require('karma-jasmine-html-reporter'),
12 | require('karma-coverage-istanbul-reporter'),
13 | require('@angular-devkit/build-angular/plugins/karma')
14 | ],
15 | client: {
16 | clearContext: false // leave Jasmine Spec Runner output visible in browser
17 | },
18 | coverageIstanbulReporter: {
19 | dir: require('path').join(__dirname, '../../coverage'),
20 | reports: ['html', 'lcovonly'],
21 | fixWebpackSourcePaths: true
22 | },
23 | reporters: ['progress', 'kjhtml'],
24 | port: 9876,
25 | colors: true,
26 | logLevel: config.LOG_INFO,
27 | autoWatch: true,
28 | browsers: ['Chrome'],
29 | singleRun: false
30 | });
31 | };
32 |
--------------------------------------------------------------------------------
/src/app/app.component.spec.ts:
--------------------------------------------------------------------------------
1 | import { TestBed, async } from '@angular/core/testing';
2 | import { AppComponent } from './app.component';
3 | describe('AppComponent', () => {
4 | beforeEach(async(() => {
5 | TestBed.configureTestingModule({
6 | declarations: [
7 | AppComponent
8 | ],
9 | }).compileComponents();
10 | }));
11 | it('should create the app', async(() => {
12 | const fixture = TestBed.createComponent(AppComponent);
13 | const app = fixture.debugElement.componentInstance;
14 | expect(app).toBeTruthy();
15 | }));
16 | it(`should have as title 'mat-ta'`, async(() => {
17 | const fixture = TestBed.createComponent(AppComponent);
18 | const app = fixture.debugElement.componentInstance;
19 | expect(app.title).toEqual('mat-ta');
20 | }));
21 | it('should render title in a h1 tag', async(() => {
22 | const fixture = TestBed.createComponent(AppComponent);
23 | fixture.detectChanges();
24 | const compiled = fixture.debugElement.nativeElement;
25 | expect(compiled.querySelector('h1').textContent).toContain('Welcome to MatTypeaheadLibrary!');
26 | }));
27 | });
28 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2020 Sanjiv Kumar
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/projects/ngx-mat-typeahead/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2020 Sanjiv Kumar
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/src/app/app.component.html:
--------------------------------------------------------------------------------
1 | NgxMatTypeahead demo app using Angular Material Input and matAutocomplete component (v6)
2 |
3 | Simple Example
4 |
5 |
6 |
8 |
9 |
10 | {{country}}
11 |
12 |
13 |
14 |
15 |
Example with
16 | allowEmptyString set as false.
17 |
18 |
20 |
21 |
22 | {{country}}
23 |
24 |
25 |
26 |
27 |
28 | Please Note: In this example if you filter by letter
29 | u , you will see 3 countries (USA, UK and Russia) as filtered output instead of 2 countries (USA, UK). This is because
30 | of the filter logic implemented by
31 | json-server . In real app scenario, the filter logic will be handled on the backend and output should be correct.
32 |
33 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "mat-typeahead-library",
3 | "version": "1.0.2",
4 | "scripts": {
5 | "ng": "ng",
6 | "start": "ng serve",
7 | "build": "ng build",
8 | "test": "ng test",
9 | "lint": "ng lint",
10 | "e2e": "ng e2e"
11 | },
12 | "private": true,
13 | "dependencies": {
14 | "@angular/animations": "^6.0.2",
15 | "@angular/cdk": "^6.1.0",
16 | "@angular/common": "^6.0.2",
17 | "@angular/compiler": "^6.0.2",
18 | "@angular/core": "^6.0.2",
19 | "@angular/forms": "^6.0.2",
20 | "@angular/http": "^6.0.2",
21 | "@angular/material": "^6.1.0",
22 | "@angular/platform-browser": "^6.0.2",
23 | "@angular/platform-browser-dynamic": "^6.0.2",
24 | "@angular/router": "^6.0.2",
25 | "core-js": "^2.5.4",
26 | "json-server": "^0.12.2",
27 | "ngx-mat-typeahead": "^1.0.2",
28 | "rxjs": "6.3.3",
29 | "zone.js": "^0.8.26"
30 | },
31 | "devDependencies": {
32 | "@angular-devkit/build-angular": "~0.6.3",
33 | "@angular-devkit/build-ng-packagr": "~0.6.3",
34 | "@angular/cli": "~6.0.3",
35 | "@angular/compiler-cli": "^6.0.2",
36 | "@angular/language-service": "^6.0.2",
37 | "@types/jasmine": "~2.8.6",
38 | "@types/jasminewd2": "~2.0.3",
39 | "@types/node": "~8.9.4",
40 | "codelyzer": "~4.2.1",
41 | "jasmine-core": "~2.99.1",
42 | "jasmine-spec-reporter": "~4.2.1",
43 | "karma": "~1.7.1",
44 | "karma-chrome-launcher": "~2.2.0",
45 | "karma-coverage-istanbul-reporter": "~1.4.2",
46 | "karma-jasmine": "~1.1.1",
47 | "karma-jasmine-html-reporter": "^0.2.2",
48 | "ng-packagr": "^3.0.0-rc.2",
49 | "protractor": "~5.3.0",
50 | "ts-node": "~5.0.1",
51 | "tsickle": "0.25.5",
52 | "tslib": "^1.7.1",
53 | "tslint": "~5.9.1",
54 | "typescript": "~2.7.2"
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/projects/ngx-mat-typeahead/src/lib/ngx-mat-typeahead.directive.spec.ts:
--------------------------------------------------------------------------------
1 | import { HttpClientTestingModule } from '@angular/common/http/testing';
2 | import { TestBed } from '@angular/core/testing';
3 | import { NgxMatTypeaheadDirective } from './ngx-mat-typeahead.directive';
4 | import { NgxMatTypeaheadService } from './ngx-mat-typeahead.service';
5 |
6 | let typeaheadService: NgxMatTypeaheadService;
7 | let directiveInstance: NgxMatTypeaheadDirective;
8 |
9 | describe('NgxMatTypeaheadDirective', () => {
10 | beforeEach(() => {
11 | TestBed.configureTestingModule({
12 | declarations: [NgxMatTypeaheadDirective],
13 | imports: [HttpClientTestingModule],
14 | providers: [NgxMatTypeaheadService]
15 | });
16 | directiveInstance = new NgxMatTypeaheadDirective(typeaheadService);
17 | typeaheadService = TestBed.get(NgxMatTypeaheadService);
18 | });
19 | it('should create an instance', () => {
20 | const directive = new NgxMatTypeaheadDirective(typeaheadService);
21 | expect(directive).toBeTruthy();
22 | });
23 | });
24 | describe('Default Inputs', () => {
25 | it('should have default value for delayTime Input variable', () => {
26 | expect(directiveInstance.delayTime).toBe(300);
27 | });
28 | it('should have default value for urlParams Input variable', () => {
29 | expect(directiveInstance.urlParams).toEqual({});
30 | });
31 | it('should have default value for urlQueryParam Input variable', () => {
32 | expect(directiveInstance.urlQueryParam).toBe('query');
33 | });
34 | it('should have default value for apiMethod Input variable', () => {
35 | expect(directiveInstance.apiMethod).toBe('get');
36 | });
37 | it('should have default value for apiType Input variable', () => {
38 | expect(directiveInstance.apiType).toBe('http');
39 | });
40 | it('should have default value for allowEmptyString Input variable', () => {
41 | expect(directiveInstance.allowEmptyString).toBe(true);
42 | });
43 | });
44 |
--------------------------------------------------------------------------------
/projects/ngx-mat-typeahead/src/lib/ngx-mat-typeahead.directive.ts:
--------------------------------------------------------------------------------
1 | import { Directive, EventEmitter, HostListener, Input, Output } from '@angular/core';
2 | import { Observable, of } from 'rxjs';
3 | import { debounceTime, distinctUntilChanged, filter, map, switchMap } from 'rxjs/operators';
4 | import { NgxMatTypeaheadService } from './ngx-mat-typeahead.service';
5 |
6 | @Directive({
7 | selector: '[NgxMatTypeahead]'
8 | })
9 | export class NgxMatTypeaheadDirective {
10 | @Input() delayTime = 300;
11 | @Input() apiURL: string;
12 | @Input() urlParams: object = {};
13 | @Input() urlQueryParam = 'query';
14 | @Input() apiMethod = 'get';
15 | @Input() apiType = 'http';
16 | @Input() callbackFuncName: string;
17 | @Input() allowEmptyString = true;
18 | @Output() filteredDataList = new EventEmitter>();
19 |
20 | private onKeyUp$: Observable;
21 |
22 | constructor(private typeAheadService: NgxMatTypeaheadService) {}
23 |
24 | @HostListener('keyup', ['$event'])
25 | onkeyup(event: KeyboardEvent) {
26 | event.preventDefault();
27 | event.stopPropagation();
28 | this.onKeyUp$ = of(event);
29 | this.showDataList(this.onKeyUp$);
30 | }
31 |
32 | private showDataList(keyUpEvent$: Observable) {
33 | keyUpEvent$
34 | .pipe(
35 | filter((e: KeyboardEvent) => this.typeAheadService.validateNonCharKeyCode(e.keyCode)),
36 | map(this.typeAheadService.extractFormValue),
37 | debounceTime(this.delayTime),
38 | distinctUntilChanged(),
39 | filter((searchTerm: string) => this.allowEmptyString || this.typeAheadService.emptyString(searchTerm)),
40 | switchMap((searchTerm: string): Observable => this.filterData(searchTerm))
41 | )
42 | .subscribe((filteredList: Array) => {
43 | this.filteredDataList.emit(filteredList);
44 | });
45 | }
46 |
47 | private filterData(searchTerm: string): Observable {
48 | return this.typeAheadService.makeApiRequest(
49 | searchTerm,
50 | this.apiURL,
51 | this.urlQueryParam,
52 | this.urlParams,
53 | this.apiMethod,
54 | this.apiType,
55 | this.callbackFuncName
56 | );
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/projects/ngx-mat-typeahead/src/lib/ngx-mat-typeahead.service.spec.ts:
--------------------------------------------------------------------------------
1 | import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
2 | import { TestBed, getTestBed, inject } from '@angular/core/testing';
3 | import { NgxMatTypeaheadService } from './ngx-mat-typeahead.service';
4 |
5 | let injector: TestBed;
6 | let ngxTypeaheadService: NgxMatTypeaheadService;
7 | let httpMock: HttpTestingController;
8 |
9 | describe('NgxMatTypeaheadService', () => {
10 | beforeEach(() => {
11 | TestBed.configureTestingModule({
12 | imports: [HttpClientTestingModule],
13 | providers: [NgxMatTypeaheadService]
14 | });
15 | injector = getTestBed();
16 | ngxTypeaheadService = injector.get(NgxMatTypeaheadService);
17 | httpMock = injector.get(HttpClientTestingModule);
18 | });
19 |
20 | it(
21 | 'should be created',
22 | inject([NgxMatTypeaheadService], (service: NgxMatTypeaheadService) => {
23 | expect(service).toBeTruthy();
24 | })
25 | );
26 | });
27 |
28 | describe('Test makeApiRequest method', () => {
29 | const dummyArgs = {
30 | searchTerm: 'c',
31 | apiURL: '../assets/countries.json',
32 | urlQueryParam: 'q',
33 | urlParams: {},
34 | apiMethod: 'get',
35 | apiType: 'http',
36 | callbackFuncName: 'jsonp_callback'
37 | };
38 | it('should return Observable', () => {
39 | spyOn(ngxTypeaheadService, 'configureParams').and.callThrough();
40 | spyOn(ngxTypeaheadService, 'checkApiMethod').and.callThrough();
41 | spyOn(ngxTypeaheadService, 'requestJsonpCall').and.callThrough();
42 | ngxTypeaheadService
43 | .makeApiRequest(
44 | dummyArgs.searchTerm,
45 | dummyArgs.apiURL,
46 | dummyArgs.urlQueryParam,
47 | dummyArgs.urlParams,
48 | dummyArgs.apiMethod,
49 | dummyArgs.apiType,
50 | dummyArgs.callbackFuncName
51 | )
52 | .subscribe(data => expect(data.length).toBe(8));
53 | });
54 | });
55 |
56 | describe('Test typeahead service util methods', () => {
57 | it('should return the character from the keyboard event', () => {
58 | const dummyEvent: KeyboardEvent = {
59 | code: 'a',
60 | target: {
61 | value: 'a'
62 | },
63 | altKey: 'a',
64 | char: 'a',
65 | charCode: 'a'
66 | };
67 | expect(ngxTypeaheadService.extractFormValue(dummyEvent)).toBe('a');
68 | });
69 | it('should return true if non empty string is passed', () => {
70 | expect(ngxTypeaheadService.emptyString('abc')).toBeTruthy();
71 | });
72 | it('should return false empty string is passed', () => {
73 | expect(ngxTypeaheadService.emptyString('')).toBeFalsy();
74 | });
75 | it('should return true if non char keycode is passed', () => {
76 | const aKeycode = 65;
77 | const enterKeyCode = 13;
78 | expect(ngxTypeaheadService.validateNonCharKeyCode(aKeycode)).toBeTruthy();
79 | expect(ngxTypeaheadService.validateNonCharKeyCode(enterKeyCode)).toBeFalsy();
80 | });
81 | });
82 |
--------------------------------------------------------------------------------
/tslint.json:
--------------------------------------------------------------------------------
1 | {
2 | "rulesDirectory": [
3 | "node_modules/codelyzer"
4 | ],
5 | "rules": {
6 | "arrow-return-shorthand": true,
7 | "callable-types": true,
8 | "class-name": true,
9 | "comment-format": [
10 | true,
11 | "check-space"
12 | ],
13 | "curly": true,
14 | "deprecation": {
15 | "severity": "warn"
16 | },
17 | "eofline": true,
18 | "forin": true,
19 | "import-blacklist": [
20 | true,
21 | "rxjs/Rx"
22 | ],
23 | "import-spacing": true,
24 | "indent": [
25 | true,
26 | "spaces"
27 | ],
28 | "interface-over-type-literal": true,
29 | "label-position": true,
30 | "max-line-length": [
31 | true,
32 | 140
33 | ],
34 | "member-access": false,
35 | "member-ordering": [
36 | true,
37 | {
38 | "order": [
39 | "static-field",
40 | "instance-field",
41 | "static-method",
42 | "instance-method"
43 | ]
44 | }
45 | ],
46 | "no-arg": true,
47 | "no-bitwise": true,
48 | "no-console": [
49 | true,
50 | "debug",
51 | "info",
52 | "time",
53 | "timeEnd",
54 | "trace"
55 | ],
56 | "no-construct": true,
57 | "no-debugger": true,
58 | "no-duplicate-super": true,
59 | "no-empty": false,
60 | "no-empty-interface": true,
61 | "no-eval": true,
62 | "no-inferrable-types": [
63 | true,
64 | "ignore-params"
65 | ],
66 | "no-misused-new": true,
67 | "no-non-null-assertion": true,
68 | "no-shadowed-variable": true,
69 | "no-string-literal": false,
70 | "no-string-throw": true,
71 | "no-switch-case-fall-through": true,
72 | "no-trailing-whitespace": true,
73 | "no-unnecessary-initializer": true,
74 | "no-unused-expression": true,
75 | "no-use-before-declare": true,
76 | "no-var-keyword": true,
77 | "object-literal-sort-keys": false,
78 | "one-line": [
79 | true,
80 | "check-open-brace",
81 | "check-catch",
82 | "check-else",
83 | "check-whitespace"
84 | ],
85 | "prefer-const": true,
86 | "quotemark": [
87 | true,
88 | "single"
89 | ],
90 | "radix": true,
91 | "semicolon": [
92 | true,
93 | "always"
94 | ],
95 | "triple-equals": [
96 | true,
97 | "allow-null-check"
98 | ],
99 | "typedef-whitespace": [
100 | true,
101 | {
102 | "call-signature": "nospace",
103 | "index-signature": "nospace",
104 | "parameter": "nospace",
105 | "property-declaration": "nospace",
106 | "variable-declaration": "nospace"
107 | }
108 | ],
109 | "unified-signatures": true,
110 | "variable-name": false,
111 | "whitespace": [
112 | true,
113 | "check-branch",
114 | "check-decl",
115 | "check-operator",
116 | "check-separator",
117 | "check-type"
118 | ],
119 | "no-output-on-prefix": true,
120 | "use-input-property-decorator": true,
121 | "use-output-property-decorator": true,
122 | "use-host-property-decorator": true,
123 | "no-input-rename": true,
124 | "no-output-rename": true,
125 | "use-life-cycle-interface": true,
126 | "use-pipe-transform-interface": true,
127 | "component-class-suffix": true,
128 | "directive-class-suffix": true
129 | }
130 | }
131 |
--------------------------------------------------------------------------------
/src/polyfills.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * This file includes polyfills needed by Angular and is loaded before the app.
3 | * You can add your own extra polyfills to this file.
4 | *
5 | * This file is divided into 2 sections:
6 | * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
7 | * 2. Application imports. Files imported after ZoneJS that should be loaded before your main
8 | * file.
9 | *
10 | * The current setup is for so-called "evergreen" browsers; the last versions of browsers that
11 | * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera),
12 | * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.
13 | *
14 | * Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html
15 | */
16 |
17 | /***************************************************************************************************
18 | * BROWSER POLYFILLS
19 | */
20 |
21 | /** IE9, IE10 and IE11 requires all of the following polyfills. **/
22 | // import 'core-js/es6/symbol';
23 | // import 'core-js/es6/object';
24 | // import 'core-js/es6/function';
25 | // import 'core-js/es6/parse-int';
26 | // import 'core-js/es6/parse-float';
27 | // import 'core-js/es6/number';
28 | // import 'core-js/es6/math';
29 | // import 'core-js/es6/string';
30 | // import 'core-js/es6/date';
31 | // import 'core-js/es6/array';
32 | // import 'core-js/es6/regexp';
33 | // import 'core-js/es6/map';
34 | // import 'core-js/es6/weak-map';
35 | // import 'core-js/es6/set';
36 |
37 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */
38 | // import 'classlist.js'; // Run `npm install --save classlist.js`.
39 |
40 | /** IE10 and IE11 requires the following for the Reflect API. */
41 | // import 'core-js/es6/reflect';
42 |
43 |
44 | /** Evergreen browsers require these. **/
45 | // Used for reflect-metadata in JIT. If you use AOT (and only Angular decorators), you can remove.
46 | import 'core-js/es7/reflect';
47 |
48 |
49 | /**
50 | * Web Animations `@angular/platform-browser/animations`
51 | * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari.
52 | * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0).
53 | **/
54 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`.
55 |
56 | /**
57 | * By default, zone.js will patch all possible macroTask and DomEvents
58 | * user can disable parts of macroTask/DomEvents patch by setting following flags
59 | */
60 |
61 | // (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame
62 | // (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick
63 | // (window as any).__zone_symbol__BLACK_LISTED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames
64 |
65 | /*
66 | * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js
67 | * with the following flag, it will bypass `zone.js` patch for IE/Edge
68 | */
69 | // (window as any).__Zone_enable_cross_context_check = true;
70 |
71 | /***************************************************************************************************
72 | * Zone JS is required by default for Angular itself.
73 | */
74 | import 'zone.js/dist/zone'; // Included with Angular CLI.
75 |
76 |
77 |
78 | /***************************************************************************************************
79 | * APPLICATION IMPORTS
80 | */
81 |
--------------------------------------------------------------------------------
/projects/ngx-mat-typeahead/src/lib/ngx-mat-typeahead.service.ts:
--------------------------------------------------------------------------------
1 | import { HttpClient, HttpParams } from '@angular/common/http';
2 | import { Injectable } from '@angular/core';
3 | import { Observable } from 'rxjs';
4 | import { map } from 'rxjs/operators';
5 | import { Key, validHttpMethods } from './ngx-mat-typeahead-util';
6 |
7 | @Injectable({
8 | providedIn: 'root'
9 | })
10 | export class NgxMatTypeaheadService {
11 | constructor(private http: HttpClient) {}
12 | /**
13 | * Extract the characters typed in the input of the typeahead component.
14 | */
15 | extractFormValue(event: KeyboardEvent): string {
16 | return event['target']['value'];
17 | }
18 |
19 | emptyString(inputSearchTerm: string): boolean {
20 | return inputSearchTerm.length > 0;
21 | }
22 |
23 | validateNonCharKeyCode(keyCode: number): boolean {
24 | return [Key.Enter, Key.Tab, Key.Shift, Key.ArrowLeft, Key.ArrowUp, Key.ArrowRight, Key.ArrowDown].every(
25 | codeKey => codeKey !== keyCode
26 | );
27 | }
28 |
29 | /**
30 | * This method configure the api call params, validates api method and makes http/jsonp call.
31 | * @param searchTerm - The search term coming from the the input.
32 | * @param apiURL - The URL that will be used to make API call.
33 | * @param urlQueryParam - The query parameter used in the URL.
34 | * @param urlParams - Any additional params as general object type of form {key: string, value: any}
35 | * @param apiMethod - GET, POST, etc. Default is `GET`
36 | * @param apiType - API method `http/jsonp`
37 | * @param callbackFuncName - callback function name.
38 | * @returns - Returns the result of Observable type.
39 | */
40 | makeApiRequest(
41 | searchTerm: string,
42 | apiURL: string,
43 | urlQueryParam: string,
44 | urlParams: object,
45 | apiMethod: string,
46 | apiType: string,
47 | callbackFuncName: string
48 | ): Observable {
49 | const options = { params: this.configureParams(searchTerm, urlQueryParam, urlParams) };
50 | const validApiMethod = this.checkApiMethod(apiMethod);
51 | return apiType === 'http'
52 | ? this.requestHttpCall(apiURL, validApiMethod, options)
53 | : this.requestJsonpCall(apiURL, options, callbackFuncName);
54 | }
55 |
56 | private configureParams(searchTerm: string, urlQueryParam: string, urlParams: object): HttpParams {
57 | const searchParams = {
58 | [urlQueryParam]: searchTerm,
59 | ...urlParams
60 | };
61 | let Params = new HttpParams();
62 | for (const eachKey of Object.keys(searchParams)) {
63 | Params = Params.append(eachKey, searchParams[eachKey]);
64 | }
65 | return Params;
66 | }
67 |
68 | private checkApiMethod(apiMethod: string): string {
69 | const validHttpMethodsArray: Array = [
70 | validHttpMethods.GET,
71 | validHttpMethods.POST,
72 | validHttpMethods.PUT,
73 | validHttpMethods.PATCH,
74 | validHttpMethods.DELETE,
75 | validHttpMethods.REQUEST
76 | ];
77 | return validHttpMethodsArray.indexOf(apiMethod) !== -1 ? apiMethod : 'get';
78 | }
79 |
80 | private requestHttpCall(url: string, validApiMethod: string, options: { params: HttpParams }): Observable {
81 | return this.http[validApiMethod](url, options);
82 | }
83 |
84 | private requestJsonpCall(
85 | url: string,
86 | options: { params: HttpParams },
87 | callbackFuncName = 'defaultCallback'
88 | ): Observable {
89 | const params = options.params.toString();
90 | return this.http
91 | .jsonp(`${url}?${params}`, callbackFuncName)
92 | .pipe(map(this.toJsonpSingleResult), map(this.toJsonpFinalResults));
93 | }
94 |
95 | private toJsonpSingleResult(response: any) {
96 | return response[1];
97 | }
98 |
99 | private toJsonpFinalResults(results: any[]) {
100 | return results.map((result: any) => result[0]);
101 | }
102 | }
103 |
--------------------------------------------------------------------------------
/angular.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
3 | "version": 1,
4 | "newProjectRoot": "projects",
5 | "projects": {
6 | "MatTypeaheadLibrary": {
7 | "root": "",
8 | "sourceRoot": "src",
9 | "projectType": "application",
10 | "prefix": "mat-ta",
11 | "schematics": {},
12 | "architect": {
13 | "build": {
14 | "builder": "@angular-devkit/build-angular:browser",
15 | "options": {
16 | "outputPath": "dist/MatTypeaheadLibrary",
17 | "index": "src/index.html",
18 | "main": "src/main.ts",
19 | "polyfills": "src/polyfills.ts",
20 | "tsConfig": "src/tsconfig.app.json",
21 | "assets": [
22 | "src/favicon.ico",
23 | "src/assets"
24 | ],
25 | "styles": [
26 | {
27 | "input": "node_modules/@angular/material/prebuilt-themes/indigo-pink.css"
28 | },
29 | "src/styles.css"
30 | ],
31 | "scripts": []
32 | },
33 | "configurations": {
34 | "production": {
35 | "fileReplacements": [
36 | {
37 | "replace": "src/environments/environment.ts",
38 | "with": "src/environments/environment.prod.ts"
39 | }
40 | ],
41 | "optimization": true,
42 | "outputHashing": "all",
43 | "sourceMap": false,
44 | "extractCss": true,
45 | "namedChunks": false,
46 | "aot": true,
47 | "extractLicenses": true,
48 | "vendorChunk": false,
49 | "buildOptimizer": true
50 | }
51 | }
52 | },
53 | "serve": {
54 | "builder": "@angular-devkit/build-angular:dev-server",
55 | "options": {
56 | "browserTarget": "MatTypeaheadLibrary:build"
57 | },
58 | "configurations": {
59 | "production": {
60 | "browserTarget": "MatTypeaheadLibrary:build:production"
61 | }
62 | }
63 | },
64 | "extract-i18n": {
65 | "builder": "@angular-devkit/build-angular:extract-i18n",
66 | "options": {
67 | "browserTarget": "MatTypeaheadLibrary:build"
68 | }
69 | },
70 | "test": {
71 | "builder": "@angular-devkit/build-angular:karma",
72 | "options": {
73 | "main": "src/test.ts",
74 | "polyfills": "src/polyfills.ts",
75 | "tsConfig": "src/tsconfig.spec.json",
76 | "karmaConfig": "src/karma.conf.js",
77 | "styles": [
78 | {
79 | "input": "node_modules/@angular/material/prebuilt-themes/indigo-pink.css"
80 | },
81 | "src/styles.css"
82 | ],
83 | "scripts": [],
84 | "assets": [
85 | "src/favicon.ico",
86 | "src/assets"
87 | ]
88 | }
89 | },
90 | "lint": {
91 | "builder": "@angular-devkit/build-angular:tslint",
92 | "options": {
93 | "tsConfig": [
94 | "src/tsconfig.app.json",
95 | "src/tsconfig.spec.json"
96 | ],
97 | "exclude": [
98 | "**/node_modules/**"
99 | ]
100 | }
101 | }
102 | }
103 | },
104 | "MatTypeaheadLibrary-e2e": {
105 | "root": "e2e/",
106 | "projectType": "application",
107 | "architect": {
108 | "e2e": {
109 | "builder": "@angular-devkit/build-angular:protractor",
110 | "options": {
111 | "protractorConfig": "e2e/protractor.conf.js",
112 | "devServerTarget": "MatTypeaheadLibrary:serve"
113 | }
114 | },
115 | "lint": {
116 | "builder": "@angular-devkit/build-angular:tslint",
117 | "options": {
118 | "tsConfig": "e2e/tsconfig.e2e.json",
119 | "exclude": [
120 | "**/node_modules/**"
121 | ]
122 | }
123 | }
124 | }
125 | },
126 | "NgxMatTypeahead": {
127 | "root": "projects/ngx-mat-typeahead",
128 | "sourceRoot": "projects/ngx-mat-typeahead/src",
129 | "projectType": "library",
130 | "prefix": "NgxMat",
131 | "architect": {
132 | "build": {
133 | "builder": "@angular-devkit/build-ng-packagr:build",
134 | "options": {
135 | "tsConfig": "projects/ngx-mat-typeahead/tsconfig.lib.json",
136 | "project": "projects/ngx-mat-typeahead/ng-package.json"
137 | },
138 | "configurations": {
139 | "production": {
140 | "project": "projects/ngx-mat-typeahead/ng-package.prod.json"
141 | }
142 | }
143 | },
144 | "test": {
145 | "builder": "@angular-devkit/build-angular:karma",
146 | "options": {
147 | "main": "projects/ngx-mat-typeahead/src/test.ts",
148 | "tsConfig": "projects/ngx-mat-typeahead/tsconfig.spec.json",
149 | "karmaConfig": "projects/ngx-mat-typeahead/karma.conf.js"
150 | }
151 | },
152 | "lint": {
153 | "builder": "@angular-devkit/build-angular:tslint",
154 | "options": {
155 | "tsConfig": [
156 | "projects/ngx-mat-typeahead/tsconfig.lib.json",
157 | "projects/ngx-mat-typeahead/tsconfig.spec.json"
158 | ],
159 | "exclude": [
160 | "**/node_modules/**"
161 | ]
162 | }
163 | }
164 | }
165 | }
166 | },
167 | "defaultProject": "MatTypeaheadLibrary"
168 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # NgxMatTypeahead
2 |
3 | **Update**: This library is Ivy Compatible and is tested against an Angular 9 app. (check example in angular_v9 branch)
4 |
5 | * A simple typeahead `directive` to be used with Angular Material input and matAutocomplete component.
6 | * This directives enhances the funtionality of Angular Material `matAutocomplete` component and is recommended that it is used with it.
7 | * However, this directive can be used with `any other` autocomplete component.
8 | * It is developed using `Angular >=6.0.0` and its newly introduced `ng g library` schematics.
9 | * This library is part of MatTypeahead project and it is generated with [Angular CLI](https://github.com/angular/angular-cli) version 6.0.3.
10 | * Library location: `projects/ngx-mat-typeahead` directory of this repository.
11 |
12 | ## Examples/Demo
13 |
14 | * A simple Example can be found under `src/app` directory of this repository. It uses `json-server` to have a url and filter functionality.
15 |
16 | ## Installation
17 |
18 | `npm i ngx-mat-typeahead`
19 |
20 | ## API
21 |
22 | `import { NgxMatTypeaheadModule } from 'ngx-mat-typeahead'`
23 | `selector: NgxMatTypeahead`
24 |
25 | ### @Inputs()
26 |
27 | | Input | Type | Required | Description |
28 | | ---------------- | ------- | -------------------------- | --------------------------------------------------------------------------------------------------------- |
29 | | apiURL | string | **YES** | the url of a remote server that supports http/jsonp calls. |
30 | | delayTime | number | Optional, default: 300 | the debounce time for this request. |
31 | | urlParams | object | Optional, default: {} | { key: string, value: any} object as additional parameters |
32 | | urlQueryParam | string | Optional, default: 'query' | a string value which is used a query parameter in the url. Ex: `http://localhost:3000/countries?query='c` |
33 | | apiMethod | string | Optional, default: 'get' | the http/jsonp method to be used. |
34 | | apiType | string | Optional, default: 'http' | http or jsonp method types. |
35 | | callbackFuncName | string | Optional | a string value for the callback query parameter. |
36 | | allowEmptyString | boolean | Optional, default: true | if true, it allows empty strings to pass and invoke search |
37 |
38 | ### @Outputs()
39 |
40 | | Output | Type | Required | Description |
41 | | ---------------- | ---------- | -------- | ------------------------------------------------------ |
42 | | filteredDataList | Array | **YES** | emits filtered data list depending on the search term. |
43 |
44 | ## Usage
45 |
46 | 1) Register the `NgxMatTypeaheadModule` in your app module.
47 | > `import { NgxMatTypeaheadModule } from 'ngx-mat-typeahead'`
48 |
49 | ```typescript
50 | import { HttpClientModule } from '@angular/common/http';
51 | import { NgModule } from '@angular/core';
52 | import { FormsModule, ReactiveFormsModule } from '@angular/forms';
53 | import { MatAutocompleteModule, MatInputModule } from '@angular/material';
54 | import { BrowserModule } from '@angular/platform-browser';
55 | import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
56 | import { NgxMatTypeaheadModule } from 'ngx-mat-typeahead';
57 | import { AppComponent } from './app.component';
58 |
59 | @NgModule({
60 | declarations: [AppComponent],
61 | imports: [
62 | BrowserModule,
63 | BrowserAnimationsModule,
64 | FormsModule,
65 | ReactiveFormsModule,
66 | MatInputModule,
67 | MatAutocompleteModule,
68 | HttpClientModule,
69 | NgxMatTypeaheadModule
70 | ],
71 | providers: [],
72 | bootstrap: [AppComponent]
73 | })
74 | export class AppModule {}
75 | ```
76 |
77 | 2) Use the directive `(NgxMatTypeahead)` in your component.
78 |
79 | ```typescript
80 | import { Component, OnInit } from '@angular/core';
81 | import { FormControl, FormGroup } from '@angular/forms';
82 | import { AppService } from './app.service';
83 | @Component({
84 | selector: 'mat-ta-root',
85 | template: `NgxMatTypeahead demo app using Angular Material
86 |
87 |
88 |
90 |
91 |
92 | {{country}}
93 |
94 |
95 |
96 |
97 | `,
98 | styleUrls: ['./app.component.css']
99 | })
100 | export class AppComponent implements OnInit {
101 | // Paramteres for the input type are defined below. The url is generated using `json-server`.
102 | // Please run your own instance of the json-server to use the the below url.
103 | queryParam = 'q';
104 | url = 'http://localhost:3000/countries';
105 |
106 | constructor(private appService: AppService) {}
107 |
108 | testFormGroup: FormGroup = new FormGroup({ country: new FormControl('') });
109 | countries: Array = [];
110 |
111 | ngOnInit() {
112 | this.countries = ["United States", "United Kingdom", "China", "Japan", "India", "Russia", "Canada", "Brazil"];
113 | }
114 |
115 | getFilteredSuggestions(filteredDataLst: Array) {
116 | this.countries = [...filteredDataLst];
117 | }
118 | }
119 | ```
120 |
121 | ## Running the example in local env
122 |
123 | * `npm i`
124 | * Run `ng serve` for a dev server and running the demo app. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.
125 | * The demo app uses `json-server` module for enabling the url and filter funtionality. Make sure you have [json-server](https://www.npmjs.com/package/json-server#getting-started) installed and running.
126 | * Once you have installed json-server, Run: `json-server --watch db.json`. You can see it running at `http://localhost:3000`.
127 |
128 | ## Build the NgxMatTypeahead module
129 |
130 | Run `ng build NgxMatTypeahead` to build the library. The build artifacts will be stored in the `dist/ngx-mat-typeahead` directory. Use the `--prod` flag for a production build.
131 |
132 | ## Running unit tests
133 |
134 | Run `ng test NgxMatTypeahead` to execute the unit tests via [Karma](https://karma-runner.github.io).
135 |
136 | ## Credits
137 |
138 | This project is based on [ngx-typeahead](https://github.com/orizens/ngx-typeahead). I want to thank Oren Farhi from [Orizens](http://orizens.com) for open sourcing his project as it helped me to write my first simple Angular library. Also want to thanks entire [Angular](https://angular.io) team for creating this awesome framework.
139 |
--------------------------------------------------------------------------------
/projects/ngx-mat-typeahead/README.md:
--------------------------------------------------------------------------------
1 | # NgxMatTypeahead
2 |
3 | **Update**: This library is Ivy Compatible and is tested against an Angular 9 app. (check example in angular_v9 branch)
4 |
5 | * A simple typeahead `directive` to be used with Angular Material input and matAutocomplete component.
6 | * This directives enhances the funtionality of Angular Material `matAutocomplete` component and is recommended that it is used with it.
7 | * However, this directive can be used with `any other` autocomplete component.
8 | * It is developed using `Angular >=6.0.0` and its newly introduced `ng g library` schematics.
9 | * This library is part of MatTypeahead project and it is generated with [Angular CLI](https://github.com/angular/angular-cli) version 6.0.3.
10 | * Library location: `projects/ngx-mat-typeahead` directory of this repository.
11 |
12 | ## Examples/Demo
13 |
14 | * A simple Example can be found under `src/app` directory of this repository. It uses `json-server` to have a url and filter functionality.
15 |
16 | ## Installation
17 |
18 | `npm i ngx-mat-typeahead`
19 |
20 | ## API
21 |
22 | `import { NgxMatTypeaheadModule } from 'ngx-mat-typeahead'`
23 | `selector: NgxMatTypeahead`
24 |
25 | ### @Inputs()
26 |
27 | | Input | Type | Required | Description |
28 | | ---------------- | ------- | -------------------------- | --------------------------------------------------------------------------------------------------------- |
29 | | apiURL | string | **YES** | the url of a remote server that supports http/jsonp calls. |
30 | | delayTime | number | Optional, default: 300 | the debounce time for this request. |
31 | | urlParams | object | Optional, default: {} | { key: string, value: any} object as additional parameters |
32 | | urlQueryParam | string | Optional, default: 'query' | a string value which is used a query parameter in the url. Ex: `http://localhost:3000/countries?query='c` |
33 | | apiMethod | string | Optional, default: 'get' | the http/jsonp method to be used. |
34 | | apiType | string | Optional, default: 'http' | http or jsonp method types. |
35 | | callbackFuncName | string | Optional | a string value for the callback query parameter. |
36 | | allowEmptyString | boolean | Optional, default: true | if true, it allows empty strings to pass and invoke search |
37 |
38 | ### @Outputs()
39 |
40 | | Output | Type | Required | Description |
41 | | ---------------- | ---------- | -------- | ------------------------------------------------------ |
42 | | filteredDataList | Array | **YES** | emits filtered data list depending on the search term. |
43 |
44 | ## Usage
45 |
46 | 1) Register the `NgxMatTypeaheadModule` in your app module.
47 | > `import { NgxMatTypeaheadModule } from 'ngx-mat-typeahead'`
48 |
49 | ```typescript
50 | import { HttpClientModule } from '@angular/common/http';
51 | import { NgModule } from '@angular/core';
52 | import { FormsModule, ReactiveFormsModule } from '@angular/forms';
53 | import { MatAutocompleteModule, MatInputModule } from '@angular/material';
54 | import { BrowserModule } from '@angular/platform-browser';
55 | import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
56 | import { NgxMatTypeaheadModule } from 'ngx-mat-typeahead';
57 | import { AppComponent } from './app.component';
58 |
59 | @NgModule({
60 | declarations: [AppComponent],
61 | imports: [
62 | BrowserModule,
63 | BrowserAnimationsModule,
64 | FormsModule,
65 | ReactiveFormsModule,
66 | MatInputModule,
67 | MatAutocompleteModule,
68 | HttpClientModule,
69 | NgxMatTypeaheadModule
70 | ],
71 | providers: [],
72 | bootstrap: [AppComponent]
73 | })
74 | export class AppModule {}
75 | ```
76 |
77 | 2) Use the directive `(NgxMatTypeahead)` in your component.
78 |
79 | ```typescript
80 | import { Component, OnInit } from '@angular/core';
81 | import { FormControl, FormGroup } from '@angular/forms';
82 | import { AppService } from './app.service';
83 | @Component({
84 | selector: 'mat-ta-root',
85 | template: `NgxMatTypeahead demo app using Angular Material
86 |
87 |
88 |
90 |
91 |
92 | {{country}}
93 |
94 |
95 |
96 |
97 | `,
98 | styleUrls: ['./app.component.css']
99 | })
100 | export class AppComponent implements OnInit {
101 | // Paramteres for the input type are defined below. The url is generated using `json-server`.
102 | // Please run your own instance of the json-server to use the the below url.
103 | queryParam = 'q';
104 | url = 'http://localhost:3000/countries';
105 |
106 | constructor(private appService: AppService) {}
107 |
108 | testFormGroup: FormGroup = new FormGroup({ country: new FormControl('') });
109 | countries: Array = [];
110 |
111 | ngOnInit() {
112 | this.countries = ["United States", "United Kingdom", "China", "Japan", "India", "Russia", "Canada", "Brazil"];
113 | }
114 |
115 | getFilteredSuggestions(filteredDataLst: Array) {
116 | this.countries = [...filteredDataLst];
117 | }
118 | }
119 | ```
120 |
121 | ## Running the example in local env
122 |
123 | * `npm i`
124 | * Run `ng serve` for a dev server and running the demo app. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.
125 | * The demo app uses `json-server` module for enabling the url and filter funtionality. Make sure you have [json-server](https://www.npmjs.com/package/json-server#getting-started) installed and running.
126 | * Once you have installed json-server, Run: `json-server --watch db.json`. You can see it running at `http://localhost:3000`.
127 |
128 | ## Build the NgxMatTypeahead module
129 |
130 | Run `ng build NgxMatTypeahead` to build the library. The build artifacts will be stored in the `dist/ngx-mat-typeahead` directory. Use the `--prod` flag for a production build.
131 |
132 | ## Running unit tests
133 |
134 | Run `ng test NgxMatTypeahead` to execute the unit tests via [Karma](https://karma-runner.github.io).
135 |
136 | ## Credits
137 |
138 | This project is based on [ngx-typeahead](https://github.com/orizens/ngx-typeahead). I want to thank Oren Farhi from [Orizens](http://orizens.com) for open sourcing his project as it helped me to write my first simple Angular library. Also want to thanks entire [Angular](https://angular.io) team for creating this awesome framework.
139 |
--------------------------------------------------------------------------------