Updated see better aproach in
this stackblitz(sorry,I don't remember the post where I talk about it)
If you want to use ENTER to focus an element you can use a directive
@Directive({
selector: '[next-tab]',
})
export class NextTabDirective {
@Input('next-tab') nextControl: any;
@HostListener("keydown.enter", ["$event"])
onEnter(event: KeyboardEvent) {
if (this.nextControl) {
if (this.nextControl.focus) {
this.nextControl.focus();
this.nextControl.select();
event.preventDefault();
return false;
}
}
}
constructor(private control: NgControl) {
}
}
You can use in a form like
<form (submit)="Submit()">
<input #input0 [next-tab]="input1" />
<input #input1 [next-tab]="input2" />
<!--the last not have [next-tab]-->
<!-an ENTER make a submit -->
<input #input2 />
<button type="button" (click)="cancel()">Cancel</button>
<button type="submit">OK</button>
</form>
I would like not use this ugly work-around, but we can improve the directive sending as next-tab an array of controls
@Directive({
selector: '[next-tab]',
})
export class NextTabDirective {
@Input('next-tab') nextControl: any[]; //<--an array of controls
@HostListener("keydown.enter", ["$event"])
onEnter(event: KeyboardEvent) {
//find the nextControl not disabled. We check if c is defined
//This allow us to use *ngIf and not put the control
let nextControl=this.nextControl.find(c=>c && !c.disabled);
if (nextControl) {
if (nextControl.focus) {
nextControl.focus();
nextControl.select();
event.preventDefault();
return false;
}
}
}
constructor(private control: NgControl) {
}
}
The form is look like
<form (submit)="Submit()">
<!--see that we create an array-->
<input #input0 [next-tab]="[input1,input2,input3]" />
<input #input1 [next-tab]="[input2,input3]" />
<!--if only one element, we make an array of one element-->
<input #input2 [style.display]="existInput2?'inherit':'none'" [next-tab]="[input3]" />
<!--if we want make invisible control NOT use *nfIf, therefore, we must hidden and disabled too -->
<input #input3 />
<button type="button" (click)="cancel()">Cancel</button>
<button type="submit">OK</button>
</form>
Finally I put a stackblitz in https://stackblitz.com/edit/angular-v8fkkf