抱歉这个菜鸟问题...
使用 primeng pack 时,将焦点设置在控件上的推荐方法是什么?使用传统输入控件时,我设置了一个表单变量(#variable)并使用 @ViewChild 来获取对它的引用,以便我可以访问其本机元素:
this._variable.nativeElement.focus();
在使用 primeng 的控件之一时我怎样才能做同样的事情?
谢谢。
路易斯
我使用自动对焦关键字:
<input type="text" size="15" pInputText class="form-control"
formControlName="email" autofocus/>
TLDR:这取决于控件本身和周围的 html,您需要如何执行此操作。
因此,对于 PrimeNG 控件来说,答案似乎会有所不同,具体取决于您尝试具体设置焦点的控件,并且如果您的控件包含在 *ngIf 中,那么它会变得更加复杂。
到目前为止,我只使用两个控件完成了此操作,它们非常不同。
在所有情况下,您都需要使用 @ViewChild 和适当标记的 html 来获取控件:
带有 ngIf 的 HTML:
<div *ngIf="something">
<p-dropdown #dropdown></p-dropdown>
</div>
没有 ngIf 的 HTML:
<p-calendar #theCalendar></p-calendar>
@ViewChild 与 ngIf:
@ViewChild('dropdown') set content(content: Dropdown) {
console.log('dropdown set', content);
this.dropdown = content;
}
@ViewChild 没有 ngIf:
@ViewChild('theCalendar') public calendar: Calendar;
然后你可以在 ngOnInit 块中设置焦点。
对于 *ng-if/dropdown 情况,它是:
this.changeDetector.detectChanges();
if (this.dropdown) {
this.dropdown.applyFocus();
}
(变更检测器处理 *ng-if...applyFocus 是关键部分,否则)。
对于不在 *ng-if 块中的 p-calendar 控件,它看起来像这样:
window.setTimeout(() => {
console.log('setting focus now');
this.calendar.inputfieldViewChild.nativeElement.focus();
}, 10);
请注意,在这种情况下,您需要执行 window.setTimeout 来等待内部元素被填充,以便您可以使用它们来调用 focus 方法。对于日历控件本身,要设置焦点,您需要访问 inputfieldViewChild。
最终,您需要根据您的个人情况对上述内容进行某种组合。希望这能帮助指导您。
这对我来说对primeng的任何组件都有效
由于每个组件都有一个属性“inputId”,因此您所需要做的就是单击与您想要聚焦的组件关联的标签。
例如:(我的所有表单都有这种布局,但您可以创建一个隐藏标签以使其工作)
<label #someComponentLabel for="component-id">Username</label>
<ng-component inputId="component-id" type="text" pInputText [(ngModel)]="value"></ng-component>
然后取决于您的组件结构和生命周期:
@ViewChild('someComponentLabel') componentLabel: ElementRef;
public load() {
setTimeout(() => this.componentLabel.nativeElement.click(), 0);
}
就我而言,我需要额外的更改检测,您可能需要也可能不需要。干杯!
最后这对我有用:
import { InputText } from 'primeng/inputtext';
<input type="text" pInputText #myInput />
// InputText from primeng/inputtext
@ViewChild('myInput') myInput: InputText;
在 .ts 方法中执行 focus() :
myInput.nativeElement.focus();