简体   繁体   中英

Set focus to dynamically created input in reactive form angular

First toggle Items to yes, then click on "add row" button. New row will be created, it should always set focus on last created name input field. Here is the stackblitz link set focus on name field

Picture depicts the scenario

You can create custom directive to get input element reference then call focus method on it.

Try this:

import { Directive,ElementRef } from '@angular/core';
import { AfterViewInit } from '@angular/core/src/metadata';

@Directive({
  selector: '[appAutoFocus]'
})
export class AutoFocusDirective implements AfterViewInit {

  constructor(private element:ElementRef) {}

   ngAfterViewInit(){
     this.element.nativeElement.focus();
   }
} 

Forked Working Stackblitz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM