Coder Social home page Coder Social logo

korniychuk / angular-autofocus-fix Goto Github PK

View Code? Open in Web Editor NEW
38.0 3.0 9.0 1.35 MB

Angular 5+ directive for fix autofocus on dynamically created controls (*ngIf, *ngFor, etc.). Uses native [autofocus] selector, no need to change your HTML template. Doesn't use any dependencies.

License: MIT License

JavaScript 16.09% TypeScript 80.59% HTML 2.98% CSS 0.34%
angular-autofocus angular2-autofocus ng-autofocus ng2-autofocus angular angular2 ng ng2 autofocus autofocus-directive

angular-autofocus-fix's Introduction

ngx-autofocus-fix

CircleCI Coverage Status npm version npm downloads Known Vulnerabilities

Angular 5+ directive for fix autofocus on dynamically created controls (*ngIf, *ngFor, etc.).
legacy version for Angular 2/4

Online Demo (Stackblitz.com)

Autofocus Demo

Advantages over the other libraries

  • Uses native HTML attribute autofocus as the selector! example
  • There are no custom selectors, no need to change your HTML template.
  • Works with native DOM. Doesn't use any dependencies(jQuery, lodash, etc.).
  • Configurable. Use can use input attributes or provide global options via AutofocusFixConfig
  • 100% Coverage, over 60 unit tests.
  • E2E tests for 8,7,6 and 5 versions of Angular including e2e test for Angular Material Input.
  • The library understands an extensive list of input data. (null/NaN/'true'/[]/...). See Advanced examples
  • Supports asynchronous focusing(optionally wrapping .focus() execution with setTimeout()).
  • Works perfectly with Angular Material. (there is an E2E test)
  • Works with AOT mode. (tested via E2E test)

Installation

Notice: npm package renamed angular-autofocus-fix -> ngx-autofocus-fix

To install this library, run:

$ npm i ngx-autofocus-fix --save

or

$ yarn add ngx-autofocus-fix

Quick start

  1. Import the library in your Angular application, for example in AppModule:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AutofocusFixModule } from 'ngx-autofocus-fix'; // <--- new code

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,

    AutofocusFixModule.forRoot(), // <--- new code
  ],
  providers: [],
  bootstrap: [ AppComponent ]
})
export class AppModule { }
  1. You can now use autofocus directive in app.component.html
<input autofocus
       placeholder="I have autofocus"
       *ngIf="showInput"
>
<button (click)="showInput = !showInput">Toggle Input</button>

Advanced examples

Ways to disable autofocus: any js-falsy value, except an empty string (default @Input's normalization mode)

   <!-- with data binding -->
   <input [autofocus]=""> <!-- undefined value -->
   <input [autofocus]="undefined">
   <input [autofocus]="false">
   <input [autofocus]="null">
   <input [autofocus]="0">
   <input [autofocus]="NaN">
   
   <!-- without data binding -->
   <input autofocus="undefined">
   <input autofocus="false">
   <input autofocus="null">
   <input autofocus="0">
   <input autofocus="NaN">
   
   <input> <!-- disabled by default -->

Ways to enable autofocus: any js-truthy value and an empty string (default @Input's normalization mode)

   <!-- an empty string will enable autofocus, this is default HTML behavior -->
   <input [autofocus]="''">
   <input autofocus="">
   <input autofocus> <!-- this is an empty string too -->
   
   <input autofocus="autofocus">
   
   <input [autofocus]="true">
   <input [autofocus]="1">
   <input autofocus="true">
   
   <input [autofocus]="'any other values'">
   <input autofocus="any other values">

   <input [autofocus]="{}">
   <input [autofocus]="[]">

Input's Smart Empty Check normalization mode

All input values are passed through the function: normalizeInputAsBoolean(value: any, smartEmptyCheck = false): boolean.

Smart Empty Check mode changes the behavior so that the following values are treated as falsy:

  • An empty string ''
  • An empty object {}
  • An empty array []

See Configuration to understand how to enable the mode.

Notes:

  • Smart Empty Check normalization mode available only for autofocus attribute. All other directive @Input's always works in the default normalization mode.
  • Using attribute autofocus without any value doesn't enable autofocusing in Smart Empty Check mode. Because of an empty value means an empty string in terms of Angular templates syntax.

Configuration

Options

export class AutofocusFixConfig {
  ...

  /**
   * In case `true` .focus() events will be wrapped by `setTimeout(() => ...)`.
   *
   * Notice:
   * I'm not sure that the action is a good practice, however this ability added because of next issues:
   * - https://github.com/korniychuk/angular-autofocus-fix/issues/1
   * - https://github.com/spirosikmd/angular2-focus/issues/46
   */
  public readonly async: boolean = false;
  /**
   * In case `true`: treat an empty string, an empty array and an empty object as a falsy value.
   * In case `false`(default): each of these values treats as truthy.
   */
  public readonly smartEmptyCheck: boolean = false;
  /**
   * In case `true`: trigger {@link ChangeDetectorRef.detectChanges}() after {@link HTMLElement.focus}().
   *
   * This is helpful in the case when the HTMLElement to which {@link AutofocusFixDirective} added
   * wrapped by another directive/component that has some binding related to focus of the element.
   * In this case without enabling .triggerChangeDetection option Angular throws ExpressionChangedAfterItHasBeenCheckedError.
   *
   * A striking example is the <mat-form-field> from the Angular Material that wraps <input> control.
   */
  public readonly triggerDetectChanges: boolean = false;
}

There are four ways to configure the AutofocusFixDirective:

1. Specify attribute-options for specific HTML Element

<input type="text"
       autofocus
       autofocusFixAsync
       autofocusFixSmartEmptyCheck
       autofocusFixTriggerDetectChanges
>

Normalization(only default) available and binding supported.

<input type="text"
       autofocus
       [autofocusFixAsync]="true"
       [autofocusFixSmartEmptyCheck]="true"
       [autofocusFixTriggerDetectChanges]="true"
>

<input type="text"
       autofocus
       autofocusFixAsync="true"
       [autofocusFixSmartEmptyCheck]="isSmart"
       autofocusFixTriggerDetectChanges="a truthy value"
>

2. Specify global options for the whole application by passing it to .forRoot({ ... })

@NgModule({
  ...
  imports: [
    ...
    AutofocusFixModule.forRoot({
      async: true,
      smartEmptyCheck: true,
      triggerDetectChanges: true,
    }),
  ],
  ...
})
export class AppModule { }

3. Provide Lazy-Route level AutofocusFixConfig config

import { NgModule } from '@angular/core';
import { AutofocusFixModule, AutofocusFixConfig } from 'ngx-autofocus-fix';


const autofocusFixConfigProvider: Provider = {
  provide: AutofocusFixConfig,
  useValue: new AutofocusFixConfig({
    async: true,
    smartEmptyCheck: true,
    triggerDetectChanges: true,
  }),
};

@NgModule({
  ...
  imports: [
    ...
    AutofocusFixModule,
  ],
  providers: [ autofocusFixConfigProvider ],
})
export class MyLazyLoadableModule { }

4. Provide Component level AutofocusFixConfig config

import { Component, Provider } from '@angular/core';
import { AutofocusFixConfig } from 'ngx-autofocus-fix';

const autofocusFixConfigProvider: Provider = {
  provide: AutofocusFixConfig,
  useValue: new AutofocusFixConfig({
    async: true,
    smartEmptyCheck: true,
    triggerDetectChanges: true,
  }),
};

@Component({
  ...
  providers: [ autofocusFixConfigProvider ],
})
export class MyComponent {}

Development

Build the library:

$ npm run build

Publish the library:

cd dist/ngx-autofocus-fix
npm publish

To lint all *.ts files:

$ npm run lint

To run library unit-tests:

$ npm run test-lib

To run e2e tests:

$ npm run e2e -- --prod=true

To run local dev server http://localhost:4200:

$ npm start
$ npm run serve:prod -- angular-8-test # AoT & Prod env

Author


Anton Korniychuk

angular-autofocus-fix's People

Contributors

dependabot[bot] avatar felipeplets avatar korniychuk 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

Watchers

 avatar  avatar  avatar

angular-autofocus-fix's Issues

Angular 10 support

Describe the bug
Currently the library does not support Angular 10, when compiling a project using Angular 10 the following error is issued:

Error: Failed to compile entry-point @my/angular-components (es2015 as esm2015) due to compilation errors:
node_modules/ngx-autofocus-fix/lib/autofocus-fix.module.d.ts:6:52 - error NG6005: AutofocusFixModule.forRoot returns a ModuleWithProviders type without a generic type argument. Please add a generic type argument to the ModuleWithProviders type. If this occurrence is in library code you don't control, please contact the library authors.

6     static forRoot(options?: AutofocusFixOptions): ModuleWithProviders;

To Reproduce
Steps to reproduce the behavior:

  1. Install this library as a dependency in a project using Angular 10
  2. ng build --prod
  3. See error

Expected behavior
No error

Errors with Angular Material

Getting this error when using autofocus with mat-form-field input:
ExpressionChangedAfterItHasBeenCheckedError Expression has changed after it was checked. Previous value: 'false'. Current value: 'true'.

Angular 4.4.6
Angular Material 2.0.0-beta.12

Angular 5

Hi!
Can I count on this plugin to be updated for Angular 5?
I use it in an internal corporate project alongside Angular 5.2.6 and it works as expected, though Angular dependency version number is set for 4.x.

Probably it's just a quick dependency version bump for you :)

Re-focus after form submit

Is your feature request related to a problem? Please describe.
No.

Describe the solution you'd like
Using Angular Reactive Form, I am accepting continues data entry on same page where user "Submit" the data after every transaction. Once submitted, I'd like to set the focus back to the control with "autofocus" attribute. I don't know how I can achieve this.

Describe alternatives you've considered
So far I am using ElementRef to re-focus. I'd be nice since this is autofocus fix.

Additional context
Thank you for making this feature.

build fails for the latest node.js

To Reproduce
Steps to reproduce the behavior:

  1. install the latest node.js 15.13.0
  2. create new project, use autofocus package
  3. close all editors, delete node_modules
  4. run npm install --silent"

Expected behavior
build fails, in output we can see
npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE package: '[email protected]',
npm WARN EBADENGINE required: { node: '>=8.0.0 <13.0.0' },
npm WARN EBADENGINE current: { node: 'v15.13.0', npm: '7.8.0' }
npm WARN EBADENGINE }

Desktop (please complete the following information):

  • Windows 10

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.