Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

primeng: Setting focus on control

sorry for the noob question...

what's the recommended way of setting the focus on a control when using the primeng pack? When using a traditional input control, I set up a form variable (#variable) and use the @ViewChild to get a reference to it so that I can access its native element:

this._variable.nativeElement.focus();

How can I do the same when using one of primeng's controls?

Thanks.

Luis

like image 686
Luis Abreu Avatar asked Feb 05 '23 13:02

Luis Abreu


2 Answers

I use the autofocus keyword:

<input type="text" size="15" pInputText class="form-control"
       formControlName="email" autofocus/>
like image 66
John Baird Avatar answered Feb 20 '23 01:02

John Baird


TLDR: It depends on the control itself and the surrounding html how you need to do this.

So, for the PrimeNG controls specifically, the answer seems to vary depending on which control you're trying to set focus on specifically, and if your control is wrapped in an *ngIf, then it becomes even more complicated.

So far I've only done this with two controls and they're very different.

In all cases, you need to acquire the control using @ViewChild with appropriately tagged html:

HTML with ngIf:

<div *ngIf="something">
<p-dropdown #dropdown></p-dropdown>
</div>

HTML without ngIf:

<p-calendar #theCalendar></p-calendar>

@ViewChild with ngIf:

@ViewChild('dropdown') set content(content: Dropdown) {
    console.log('dropdown set', content);
    this.dropdown = content;
}

@ViewChild without ngIf:

@ViewChild('theCalendar') public calendar: Calendar;

Then you can set focus in the ngOnInit block.

For the *ng-if/dropdown case, it's:

this.changeDetector.detectChanges();
if (this.dropdown) {
    this.dropdown.applyFocus();
}

(The change detector handles the *ng-if... the applyFocus is the critical part otherwise).

For the p-calendar control not in a *ng-if block it looks like this:

window.setTimeout(() => {
    console.log('setting focus now');
    this.calendar.inputfieldViewChild.nativeElement.focus();
}, 10);

Note that, in this case, you need to do a window.setTimeout to wait for the inner elements to be populated so that you can use them to call the focus method. For the calendar control itself, to set focus, you need to access the inputfieldViewChild.

Ultimately, you'll need some combination of the above for your individual situation. Hopefully this will help guide you.

like image 20
Reginald Blue Avatar answered Feb 20 '23 02:02

Reginald Blue