【发布时间】:2021-07-27 18:23:47
【问题描述】:
我尝试在我的应用程序的许多输入中激活焦点。我想我会创建一个自定义指令,而不是复制代码,但我做不到。 如果有人可以帮助我.. 这是我的错误代码: 指令:
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>
非常感谢
【问题讨论】:
-
你很亲密。在构造函数中传递元素
constructor(private host: ElementRef) {},然后您可以使用this.host.nativeElement.focus();访问它