angular - 多次调用 ngAfterViewInit()?
问题描述
我的应用程序使用了我分解的材料步进器,以便能够在多个组件中调用它。
我希望默认启用此步进器的第一个字段的焦点。我做了这样的事情,但只有当我启动应用程序或刷新时。一旦我在应用程序中四处走动并转到使用此步进器的页面,我就会失去这种专注。
这是不起作用的步进器的代码:
Html(仅第一个字段)
<mat-vertical-stepper class="vertical-stepper" [linear]="isLinear" #stepper (selectionChange)="onChange($event)">
<mat-step [stepControl]="firstFormGroup" label="Scannez une référence">
<form [formGroup]="firstFormGroup">
<ng-template matStepLabel>{{ 'ZONE.CODE_BARRE_REF' | translate }}</ng-template>
<div class="flexInput">
<mat-form-field appearance="outline" class="mat-form-zone">
<input matInput id="input0" autocomplete="off" formControlName="reference"
placeholder="{{ 'ZONE.CODE_BARRE_REF_PLACEHOLDER' | translate }}" required>
</mat-form-field>
<button mat-mini-fab color="primary" (click)="onCheckRef()" matStepperNext aria-label="">
<mat-icon>done</mat-icon>
</button>
</div>
</form>
</mat-step>
和 ts :
@ViewChild('stepper') stepper: MatStepper;
constructor(private formBuilder: FormBuilder,
private rayonService: SharedRayonService) {
}
ngOnInit() {
this.initStepperForm();
}
ngAfterViewInit() {
this.setFocus();
}
onChange(event) {
let index = String(event.selectedIndex);
this.targetInput = 'input' + index;
if (index === "0") this.rayonService.isDisplayProductSubject.next(false);
else if (index === "1") this.rayonService.isDisplayProductSubject.next(true);
this.setFocus();
}
setFocus() {
let targetCurrentInput = document.getElementById(this.targetInput);
console.log(targetCurrentInput);
setTimeout(function waitTargetElem() {
if (document.body.contains(targetCurrentInput)) {
targetCurrentInput.focus();
} else {
setTimeout(waitTargetElem, 100);
}
}, 100);
}
我在这样的几个组件中调用此代码:
<app-stepper></app-stepper>
如何恢复预期的行为(关注组件每次调用中的第一个字段)?
解决方案
推荐阅读
- android - Kotlin 在片段中隐藏 appbarlayout
- javascript - 如何使用jquery在另一个元素内添加元素
- python - Python中的序列计数
- office365 - Outlook 加载项在 Outlook 日历中不可见
- angular - 使用角度路由时,NVDA 将未访问的链接读取为已访问的链接
- reactjs - 为什么上传的图片显示问号?如何在本机反应中将图像上传到服务器
- android - 如何动态创建相机预览?
- google-api - 谷歌选择器,即使被过滤,也会显示指向不属于我的文件的快捷方式
- php - Laravel 8 - 此集合实例上不存在属性 [名称]
- javascript - 模态框内的提交按钮