0
votes

I have a input field which I set focus to when my view loads in the following way:

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

this works fine from within the ngAfterViewInit() function but when I try to do it in another part of my view when a button is clicked I get an exception saying that focusInput is undefined. After reading up a bit it seems like ngIf could be the cause of this as the part of the view that contains the input field #focusInput gets shown or hidden using ngIf. Is there any way I can check using ngOnChanges() or anything else whether the #focusInput input field is currently shown and if it is set focus to it?

3
@yurzui I don't completely understand. So I can set the reference to that html input field before I set focus on it using a setter function? - user2094257
Create plunker that demonstrates your problem. As you said you use ngIf. So that is why your reference null when ngIf returns false. setter will help you to recognize whether reference undefined or not - yurzui
The thing is when I try to set focus that element is displayed so that won't help. It seems it's only defined in ngAfterViewInit(). Is there a way for me to re-initialize it using a setter so it's not undefined?hel - user2094257
In setter you will get value. If it is not undefined you can set focus - yurzui

3 Answers

1
votes

It happens when you have ngIf or ngFor directives inside your template and your input can not be linked to focusInput property you added inside your class. Instead use this code:

<input type="text" #myInput />
{{ myInput.focus() }}

Just add {{ myInput.focus() }} right after input inside template

0
votes

The simplest solution turned out to be writing a custom focus attribute directive. This helped a lot:

How to move focus on form elements the Angular way

0
votes

I know its very late to answer your question. If you want focus after any click or view change so for this you need to call change detector. You can call change detection after your view change or a click by calling detectchanges().

`constructor(private detRef:ChangeDetectorRef) {}
  @ViewChild('name_input') input: ElementRef;

    private buttonClick(): void {
      this.detRef.detectChanges();
      this.input.nativeElement.focus();
    }`

Hope this will helpful.