ViewChild and focus()

ぃ、小莉子 提交于 2019-12-05 15:55:43

Bindings are only updated when change detection runs, which is usually after an event handler completed. This is to late for your use case, because the event handler itself depends already on the effect of change detection.

You can enforce change detection immediately (synchronically) by calling detectChanges()

constructor(private cdRef:ChangeDetectorRef) {}

@ViewChild('myname') input: ElementRef;
...
private toggleEditable(): void {
  this.whyModel.toggleEditable();
  this.cdRef.detectChanges();
  this.input.nativeElement.focus();
}

You can also 'force' the focus with AfterViewCheck. I simplified your code for the demo purposes:

Typescript:

  editable;

  @ViewChild('myname') input: ElementRef;
  private toggleEditable(): void {
      this.editable = !this.editable;
   }

   ngAfterViewChecked(){
     if(this.editable){
          this.input.nativeElement.focus();
     }
   }

HTML

<div class="action ui-g-2" (click)="toggleEditable()">edit</div>
<br>
<textarea [hidden]="!editable" #myname id="textBox_{{id}}" pInputTextarea
   focus="true" [(ngModel)]="description"></textarea>

Stackblitz example

Akshay Yadav

You can use @ViewChild and focus() to focus on a particular element. It can be used like this:

In HTML file (abc.component.html)

<form #data="ngForm">
<input class="text-field" type="text" name="name" >
<input class="text-field" type="text" name="surname">
<input class="text-field" type="text" name="company">
</form>


<button type="submit" value="Submit" (click)="submitData(data.value)">Submit</button>


<input class="text-field" type="text" name="City" #setFocusField>
<input class="text-field" type="text" name="State">

In TypeScript file (abc.component.ts)

@ViewChild('setFocusField') setFocusField: any;

submitData(data:any){
  this.setFocusField.focus();
}

When you click on the submit button, the focus will be set to the field "City".

Another way to achieve this:

In above code, instead of any on ViewChild field, we can use ElementRef.

In that case typescript file changes will be as follow:

(abc.component.ts)

@ViewChild('setFocusField') setFocusField: ElementRef;

submitData(data:any){
  this.setFocusField.nativeElement.focus();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!