primeng: Setting focus on control

不羁岁月 提交于 2020-12-12 12:22:10

问题


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


回答1:


I use the autofocus keyword:

<input type="text" size="15" pInputText class="form-control"
       formControlName="email" autofocus/>



回答2:


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.



来源:https://stackoverflow.com/questions/41042513/primeng-setting-focus-on-control

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!