diff --git a/components/input-number/nz-input-number.component.ts b/components/input-number/nz-input-number.component.ts index f65e55c61ba..a7cf50fe039 100644 --- a/components/input-number/nz-input-number.component.ts +++ b/components/input-number/nz-input-number.component.ts @@ -104,12 +104,10 @@ export class NzInputNumberComponent implements ControlValueAccessor, AfterViewIn } updateAutoFocus(): void { - if (this.isInit) { - if (this.nzAutoFocus) { - this.renderer.setAttribute(this.inputElement.nativeElement, 'autofocus', 'autofocus'); - } else { - this.renderer.removeAttribute(this.inputElement.nativeElement, 'autofocus'); - } + if (this.nzAutoFocus) { + this.renderer.setAttribute(this.inputElement.nativeElement, 'autofocus', 'autofocus'); + } else { + this.renderer.removeAttribute(this.inputElement.nativeElement, 'autofocus'); } } @@ -365,5 +363,8 @@ export class NzInputNumberComponent implements ControlValueAccessor, AfterViewIn ngAfterViewInit(): void { this.isInit = true; + if (this._autoFocus) { + this.focus(); + } } } diff --git a/components/input-number/nz-input-number.spec.ts b/components/input-number/nz-input-number.spec.ts index 05576fb8470..022bec36a26 100644 --- a/components/input-number/nz-input-number.spec.ts +++ b/components/input-number/nz-input-number.spec.ts @@ -1,5 +1,5 @@ import { Component, ViewChild } from '@angular/core'; -import { fakeAsync, flush, TestBed } from '@angular/core/testing'; +import { fakeAsync, flush, TestBed, tick } from '@angular/core/testing'; import { FormsModule, FormBuilder, FormGroup, ReactiveFormsModule } from '@angular/forms'; import { By } from '@angular/platform-browser'; @@ -57,7 +57,10 @@ describe('input number', () => { it('should autofocus work', () => { fixture.detectChanges(); testComponent.autofocus = true; + testComponent.nzInputNumberComponent._autoFocus = true; + testComponent.nzInputNumberComponent.ngAfterViewInit(); fixture.detectChanges(); + expect(inputElement === document.activeElement).toBe(true); expect(inputElement.attributes.getNamedItem('autofocus').name).toBe('autofocus'); testComponent.autofocus = false; fixture.detectChanges();