创建一个指令来启用对输入字段的关注



我尝试在应用程序的许多输入中激活焦点。而不是复制代码,我想我会创建一个自定义指令,但我不能。如果有人能帮我…这是我的错误代码:指令:

import { AfterViewInit, Directive, ElementRef, ViewChild } from '@angular/core';
@Directive({
selector: '[appFocus]'
})
export class FocusDirective implements AfterViewInit {
@ViewChild('zone') zoneInput: ElementRef;
constructor() { }
ngAfterViewInit() {
this.zoneInput.nativeElement.focus();
}
}

模板中的:

<div>
<mat-form-field class="example-full-width" appearance="fill">
<mat-label>Saisie code barre</mat-label>
<input appFocus matInput formControlName="barcode" placeholder="EAN...">
</mat-form-field>
</div>

Thank you very much

你很接近了!

constructor(private el: ElementRef) {}
ngAfterViewInit(): void {
this.el.nativeElement.focus();
}

您需要实际地传递元素,以便能够访问要关注的原生元素,而不是zoneInput。你可能需要也可能不需要在setTimeout中包装,但这应该能满足你的需要。

最新更新