I have a component which contains a textarea which is hidden by default :
<div class="action ui-g-2" (click)="toggleEditable()">edit</div>
<textarea [hidden]="!whyModel.inEdition" #myname id="textBox_{{whyModel.id}}" pInputTextarea focus="true" [(ngModel)]="whyModel.description"></textarea>
When I click on the "edit" div I want to show the textarea and put focus on it :
@ViewChild('myname') input: ElementRef;
...
private toggleEditable(): void {
this.whyModel.toggleEditable();
this.input.nativeElement.focus();
}
The "show" part is working but not the focus part. What do I miss?
You can use
@ViewChild
andfocus()
to focus on a particular element. It can be used like this:In HTML file (abc.component.html)
In TypeScript file (abc.component.ts)
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
onViewChild
field, we can useElementRef
.In that case typescript file changes will be as follow:
(abc.component.ts)
You can also 'force' the focus with AfterViewCheck. I simplified your code for the demo purposes:
Typescript:
HTML
Stackblitz example
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()