多次调用 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>

如何恢复预期的行为(关注组件每次调用的第一个字段)?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)