Check out the Solution
HTML Code:
<h2>Using [formControl]</h2>
<input type="text" [formControl]="myControl"> {{ myControl.value }}
<button (click)="focusToFormControl()">Focus</button>
<hr>
<h2>Using formControlName</h2>
<form [formGroup]="myForm">
<input type="text" formControlName="foo">
<button (click)="focusToFormControlName('foo')">Focus</button>
</form>
TypeScript Code:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl,FormControlDirective, FormControlName, FormGroup } from '@angular/forms';
const originFormControlNgOnChanges = FormControlDirective.prototype.ngOnChanges;
FormControlDirective.prototype.ngOnChanges = function () {
this.form.nativeElement = this.valueAccessor._elementRef.nativeElement;
return originFormControlNgOnChanges.apply(this, arguments);
};
const originFormControlNameNgOnChanges = FormControlName.prototype.ngOnChanges;
FormControlName.prototype.ngOnChanges = function () {
const result = originFormControlNameNgOnChanges.apply(this, arguments);
this.control.nativeElement = this.valueAccessor._elementRef.nativeElement;
return result;
};
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
name = 'Angular 6';
myControl = new FormControl();
myForm: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.myForm = this.fb.group({
foo: ''
});
}
focusToFormControl() {
(<any>this.myControl).nativeElement.focus();
}
focusToFormControlName(name) {
(<any>this.myForm.get(name)).nativeElement.focus();
}
}